Mark As Completed Discussion

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:

  1. createContext: This function helps create a new context object.

  2. Context Provider: It provides the data to all descendant components.

  3. 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:

JAVASCRIPT
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.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment