API
Explore how to create and use React Context API to manage and share state across your application. Learn the role of Providers and Consumers, implement multilingual support, and understand how to update context values dynamically to trigger re-renders in components.
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 ...