About
A Context1) provides a way to pass data through the component tree without having to pass props down manually at every level.
They are part of tree, normally they would encapsulate a sub-tree and would not return a visible react element but if they can't initialize, you can stop the tree building by returning null or an error message.
Example: Translation
If you want to translate your application, you can use a context.
const englishMessages = message => {
if (message == "hello.world") {
return "Hello, World!";
}
return "Not yet translated";
};
const TranslationContext = React.createContext();
const Greeting = () => {
const translate = React.useContext(TranslationContext);
return <div>
<p>{translate("hello.world")}.</p>
<p>{translate("hello.you")}.</p>
</div>;
};
const App = () => (
<TranslationContext.Provider value={englishMessages}>
<Greeting />
</TranslationContext.Provider>
);
- And render
ReactDOM.render(<App />, document.getElementById('root'));
<div id="root"><!-- called the "root" DOM node because everything inside it will be managed by React DOM --></div>
- Output:
Utility
How to know if the context is available?
function useInContext() {
return React.useContext(MyContext) != null;
}