← React Beginner Questions - Set 4 Q33
React Beginner Questions - Set 4
It reads a context value without the `<Consumer>` render prop, and subscribes the component to changes.
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>
);
}