In React, we pass data from upper to lower levels. But this approach is inconvenient when we work with global data that is needed simultaneously in many components at different levels of the hierarchy.
Such data includes the current level or color scheme. It is not convenient to transfer such data directly; you have to drag it through the entire application. We can use a context mechanism to deal with it. It allows us to pass things to the application and get access to data directly in any component, bypassing props.
The useContext()
hook allows you to use contexts inside the component. To do this, you need to perform three steps:
Initialize the context object in the same place where we initialized the application:
// We pass the default value by the parameter // We have chosen the context object's name arbitrarily const UserContext = React.createContext({});
Connect the provider and pass the data to the context object via the
value
prop:// user is the data inside the context <UserContext.Provider value={user}> <MyComponent /> </UserContext.Provider>
Get the context object data:
import React, { useContext } from 'react'; const MyComponent = () => { // Returns the entire context object const user = useContext(UserContext); return <h1>{user.name}</h1>; }
Here is another example of a context object. We store the current topic in it:
const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
const ThemeContext = React.createContext(
themes.dark, // default value
);
And somewhere inside the application:
<ThemeContext.Provider value={/* current topic */}>
<Content />
</ThemeContext.Provider>
We can store both a primitive value and an object inside the context. React does not track changing the contents of this object and therefore doesn't trigger re-rendering.
But if you replace the object itself, React will know about the change because of the changed link and will redraw the components inside the provider.
Sometimes, we store dynamic data in the context — during authorization, for example. When the user logs in, we have to save some data to provide the user with additional functions.
The context doesn't provide anything for this, but you can pass methods for manipulating data to the context and store it using useState()
.
A more advanced option is to create a provider in a separate component. This way, we can isolate the data from the entire application and transfer the interface to the components to interact with the data.
To do this, create a context in a separate module so that all components can import it:
// ThemeContext.js
import { createContext } from 'react';
export default createContext({
themes: {},
theme: {},
setTheme: () => {},
});
Creating a separate provider component:
import ThemeContext from './ThemeContext.js';
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState(themes.dark);
const setLightTheme = () => setTheme(themes.light);
const setDarkTheme = () => setTheme(themes.dark);
return (
<ThemeContext.Provider value={{ theme, setLightTheme, setDarkTheme, themes }}>
{children}
</ThemeContext.Provider>
);
};
And inside the application, we use the provider as a regular component:
<ThemeProvider>
<MyComponent />
</ThemeProvider>
In the component itself, you can now import the context object and use functions from the provider to change the state in the context:
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext.js';
const MyComponent = () => {
const { setLightTheme } = useContext(ThemeContext);
return <button onClick={() => setLightTheme()}>Activate light mode</button>;
}
Context is a convenient mechanism for certain situations, but it shouldn't become the default way to pass data around the application. This temptation appears for many who are using it for the first time. The main problem with context objects is that they bind components to global data, making it difficult to reuse them in other situations.
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.