Context API
In React, the Context API is a feature that allows you to share data between components without passing props through every level of the component tree. It is useful for managing state at a global level, making it accessible to any component that needs it.
Context API consists of three main parts:
createContext
: This function helps create a new context object.Context Provider: It provides the data to all descendant components.
Context Consumer: It allows any descendant component to access the data provided by the Context Provider.
To illustrate the usage of the Context API, consider the following example:
1// Create a context
2const MyContext = createContext();
3
4// Create a provider
5const MyProvider = ({ children }) => {
6 const [count, setCount] = useState(0);
7
8 const increment = () => {
9 setCount(count + 1);
10 };
11
12 const decrement = () => {
13 setCount(count - 1);
14 };
15
16 return (
17 <MyContext.Provider value={{ count, increment, decrement }}>
18 {children}
19 </MyContext.Provider>
20 );
21};
22
23// Consume the context
24const MyComponent = () => {
25 const { count, increment, decrement } = useContext(MyContext);
26
27 return (
28 <div>
29 <h1>Count: {count}</h1>
30 <button onClick={increment}>Increment</button>
31 <button onClick={decrement}>Decrement</button>
32 </div>
33 );
34};
35
36// Render the component tree
37ReactDOM.render(
38 <MyProvider>
39 <MyComponent />
40 </MyProvider>,
41 document.getElementById('root')
42);
In this example, the MyContext
object is created using createContext()
. The MyProvider
component wraps the MyComponent
and provides the count
value as well as the increment
and decrement
functions through the context. The MyComponent
component consumes the context using the useContext
hook and displays the count
value and two buttons to increment and decrement the count.
The Context API simplifies the process of managing state at a global level and makes it easier to share data between components. It is especially useful in larger applications where prop drilling can become cumbersome.
xxxxxxxxxx
);
// Code relevant to Context API
import React, { createContext, useState } from 'react';
// Create a context
const MyContext = createContext();
// Create a provider
const MyProvider = ({ children }) => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return (
<MyContext.Provider value={{ count, increment, decrement }}>
{children}
</MyContext.Provider>
);
};
// Consume the context
const MyComponent = () => {
const { count, increment, decrement } = useContext(MyContext);