React Context

React Context

Rect Context

React Context is a powerful feature that allows you to manage state across your entire application without having to pass props down manually at every level of the component tree.

Here are the basic steps to use React Context:

Step 1: Create the Context

First, you need to create the context. You’ll need to export it from a file so that your components can use it. createContext function takes a value as initialValue. If there is no context provider, the default value will be used.

CounterContext.js

1
2
3
4
5
6
import { createContext } from "react";

export const CounterContext = createContext({
count: 0,
setCount: (v) => {}
});

Here we provide a default object { count: 0, setCount: (v) => {} } for the CounterContext.

Step 2: Use the Context

useContext is a React Hook that lets you read and subscribe to context from your component.

ChildComponent.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { useContext } from "react";
import { CounterContext } from "./CounterContext";

export default function ChildComponent() {
const { count, setCount } = useContext(CounterContext);

return (
<div>
<div>count: {count}</div>
<div>
<button onClick={() => setCount((count) => count + 1)}>
Increment
</button>
<button onClick={() => setCount((count) => count - 1)}>
Decrement
</button>
</div>
</div>
);
}

If you don’t provide the Context, the default value will be used. in this case, the count value and setCount function from the CounterContext will be used.

Step 3: Provide the Context

Provide the context.

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { useState } from "react";
import { CounterContext } from "./CounterContext";
import ChildComponent from "./ChildComponent";

export default function App() {

const [count, setCount] = useState(0);

return (
<CounterContext.Provider value={{ count, setCount }}>
<div className="App">
<ChildComponent />
</div>
</CounterContext.Provider>
);
}

Here we provide the Context and give the value { count, setCount } created from useState Hook.

Conclusion

React Context provides a clean and efficient way to manage state in your React applications. By creating a context provider, you can encapsulate your state logic and make it accessible to any component in your application without the need for prop drilling. Understanding these basic concepts will empower you to build more complex and interactive applications using React. Happy coding!

References: