Search⌘ K

API

Explore how to create and implement React's Context API to manage state and share data within your app. Understand how to build multilingual services using Context, update values dynamically, and optimize components to consume context effectively.

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:

import React from 'react';
import LanguageContext from './LanguageContext';

const DisplaySelectedLanguage = () => (
  <LanguageContext.Consumer>
    {value => <p> The chosen language is { value } </p>}
  </LanguageContext.Consumer>
);

export default DisplaySelectedLanguage;

Although no props have been passed to the ...