API
Learn how you can allow components to share state across the entire app and avoid moving props from parent to child to grandparent.
Creating a new Context
In order to create a new Context, React provides the createContext
method:
const LanguageContext = React.createContext(defaultValue);
We have just created a new Context using this line of code. The Context now consists of a
Provider and a Consumer component. LanguageContext.Provider
as well as
LanguageContext.Consumer
.
The Context can now be used in the application by wrapping the contents of the tree within a Provider:
// LanguageContext.js
import React from 'react';
const LanguageContext = React.createContext('de');
export default LanguageContext;
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import LanguageContext from './LanguageContext';
const App = () => (
<LanguageContext.Provider value={'en'}>
{/* inside of this tree, the value of 'en' is available to other components
*/}
</LanguageContext.Provider>
);
ReactDOM.render(<App />, document.getElementById('#root'));
The SelectedLanguage
component can now be used at any point within the application. If the value within the Provider changes, all Consumer components encompassed within the Provider will render again using the updated value.
A complete if a little artificial example is this:
Get hands-on with 1400+ tech skills courses.