← React Beginner Questions - Set 4 Q33

What is the purpose of the useContext hook?

React Beginner Questions - Set 4

It reads a context value without the `<Consumer>` render prop, and subscribes the component to changes.

Example

import { createContext, useContext } from 'react';

const LocaleContext = createContext({ lang: 'en', decimals: '.' });

function Price({ amount }) {
  const { lang, decimals } = useContext(LocaleContext);
  return <p>{lang === 'es' ? amount.toFixed(2).replace('.', ',') : amount.toFixed(2)} EUR</p>;
}

// Provider somewhere above
function App() {
  return (
    <LocaleContext.Provider value={{ lang: 'es', decimals: ',' }}>
      <Price amount={19.5} />
    </LocaleContext.Provider>
  );
}

What to notice

← Back to the question list