Context API: Global State Management in React
In React, managing and passing state down multiple levels of components can be cumbersome, especially when properties need to be accessed deeply nested in the component tree. The Context API provides a solution to this problem by allowing us to share data (state) across components without having to pass it manually through props at each level.
With the Context API, we can create a context
and provide a value for that context at a higher level component. Any component that needs access to that value can then consume it using the useContext
hook.
Here's an example of creating and using a context in React:
JAVASCRIPT
1// Create a context
2const ThemeContext = createContext();
3
4// Provide a value for the context
5const App = () => {
6 return (
7 <ThemeContext.Provider value="dark">
8 <Component />
9 </ThemeContext.Provider>
10 );
11};
12
13// Use the context
14const Component = () => {
15 const theme = useContext(ThemeContext);
16
17 return (
18 <div>
19 <h1>Current Theme: {theme}</h1>
20 </div>
21 );
22};
xxxxxxxxxx
28
// Replace with code examples and explanations relevant to "Context API" topic
// Illustrate how to create a context and provide values
import React, { createContext, useContext } from 'react';
// Create a context
const ThemeContext = createContext();
// Provide a value for the context
const App = () => {
return (
<ThemeContext.Provider value="dark">
<Component />
</ThemeContext.Provider>
);
};
// Use the context
const Component = () => {
const theme = useContext(ThemeContext);
return (
<div>
<h1>Current Theme: {theme}</h1>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment