DEV Community

Geetika Bajpai
Geetika Bajpai

Posted on

React Context API

Why do we need context API.

Image description

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:

State in Component A:

Component A holds a piece of state, value: 1, and a function to update it, setCount().

Passing State through Components:

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.

Problems with Prop Drilling:

  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

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.

Simplified Code: No need to pass props through multiple layers, leading to cleaner and more understandable code.
Flexibility: 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

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

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

We will create Counter.jsx file inside context and write this.
Image description
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.

`export const CounterContext = createContext(null);`
  • 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.
CounterProvider
  • 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

Image description
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
This code defines the App component for a React application that uses the CounterContext to manage and display a shared counter state.

App Component:
  • 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.

Top comments (0)