React Context API
Published: 2024-06-26 19:19:42

## Why do we need context API.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzh4izg9t2ghosddvivp.png)

In React, passing props is a fundamental concept that enables a parent component to share data with its child components as well as other components within an application.

## Prop Drilling Explained:

<h3>State in Component A:</h3>Component A holds a piece of state, value: 1, and a function to update it, setCount().
<h3>Passing State through Components:</h3>To get the state (value) and the function (setCount()) to Component D, Component A needs to pass them as props to Component B.Component B, in turn, passes these props down to Component C.Finally, Component C passes them down to Component D.

<h2>Problems with Prop Drilling:</h2>

1. Complexity: As the number of components grows, the process of passing props through each intermediate component becomes cumbersome and error-prone.
2. Maintenance: If the state or function needs to be used by additional components at different levels, the structure must be adjusted accordingly, leading to increased complexity and reduced maintainability.

## Need for React Context API:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ykfngdr9iku90rmgrcxm.png)

React Context API allows for state to be managed and accessed at a centralized place inside context. With Context API, the state and functions can be made available directly to any component in the component tree without passing props through each intermediate component.

<u>Simplified Code:</u> No need to pass props through multiple layers, leading to cleaner and more understandable code.
<u>Flexibility:</u> State and functions can be accessed and updated by any component within the provider, making the application more flexible and easier to maintain.

Now component A and D both can access without prop drilling. If component A change the state automatically component D re-render. Because component should also be re-render with fresh data. Means whenever in our context state changes those components who are reading that re-render itself with new value.

If we need to give access of context to these components so you need to wrap inside contextProvider.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ueasaox7g42ux28euy8.png)

if we don't give contextProvider these context will not access that context state. Now, in context these components can read and write also.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yh3leg1ke5to4a52y7o2.png)

Now, we will start and see the code this increment decrement.

We will create `Counter.jsx` file inside context and write this.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6mw049rv2qtfqk202y4.png)
This code defines a React context for managing a counter state and provides a context provider component to wrap parts of the application that need access to this counter state. 

<h5>`export const CounterContext = createContext(null);`</h5>

- This line creates a context using createContext from React.
- CounterContext will be used to share state (and potentially other values) across the component tree without having to pass props down manually at every level.
- Initially, the context is set to null, meaning it has no default value.

<h5>CounterProvider</h5>

- The useState hook to create a piece of state called count and a function to update it called setCount.
- count is initialized to 0.
- Inside returns a `CounterContext.Provider` component the value prop of the provider is an object containing `count`, `setCount`, and `name: "Geet"`.
      - `count`: The current count value.
      - `setCount`: The function to update the count value.
      - `name`: "Geet": A static value just for demonstration purposes 
         (it could be anything you want to share via context).
- `{props.children}`: This ensures that any components wrapped by `CounterProvider` will be rendered inside the provider, making the context values (count, setCount, and name) available to those components.

Wrap your application (or part of it) with `CounterProvider` like this
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69t7auc96cz48pcfoggf.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2pms0xfs3bga1xtgkhr.png)
This code defines a Counter component in React that interacts with a shared counter state using the CounterContext.

- `useContext(CounterContext)` is called to access the values provided by the CounterProvider.
- `counterContext` now holds the context value, which includes the count and setCount state, and any other values provided by the context.
- The Counter component returns a div containing two buttons.
- The Increment button has an onClick handler that calls setCount with the current count incremented by 1.
- The Decrement button has an onClick handler that calls setCount with the current count decremented by 1.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aikujcslsyt0d8ok7j7r.png)
This code defines the App component for a React application that uses the CounterContext to manage and display a shared counter state.

<h5>App Component:</h5>

- Uses useContext to access the CounterContext.
- Displays the current count from the context.
- Renders four Counter components, each of which can increment and decrement the shared counter state.
- This setup demonstrates how React context can be used for state management across multiple components, providing a shared state that can be accessed and modified by any component within the context provider.