Context API in React Js

Context API allows data to be passed through a component tree without having to pass props manually at every level. This makes it easier to share data between components.

Why do we need global state management

prop drilling in react js
prop drilling in react js

In JavaScript, particularly with React, prop drilling refers to the practice of passing data from a parent component through multiple intermediate components to reach a deeply nested child component. This can lead to complex and cumbersome code when you have to pass props through many layers of components that don’t use the props themselves.

To solve this issue , we use global state management technique such as Context API , Redux ,Zustand , etc.

The Context API in React helps deal with prop drilling by allowing you to share data across components without having to pass props through every intermediary layer. Here’s how it works:

  1. Create Context: Define a context using React.createContext(). This creates a Context object that can hold the data you want to share.
  2. Provider: Wrap a component tree with the Context.Provider component. The value prop of the provider holds the data that you want to share.
  3. Consumer: Use the Context.Consumer component or the useContext hook within any nested component to access the shared data, bypassing the need to pass it through props.

This way, the context provider at a higher level supplies the data, and any descendant component can access it directly, reducing the need for prop drilling.

Step 1 – Create a Context Object

We are creating an empty context and exporting it so that it can be used by other part of the application

src/contexts/ThemeProvider.js

import { createContext } from "react";
export const ThemeContext = createContext();

Step 2 – Wrap Component with Provider

  • Defined an state
  • Passed the data as value while wrapping the complete application with context provider

App.jsx

import { ThemeContext } from "./contexts/ThemeContext";

function App() {
  const [text, setText] = useState("");
  return (
    <ThemeContext.Provider value={{ text, setText }}>
      <A />
      <B />
    </ThemeContext.Provider>
  );
}

export default App;

Why 2 parenthesis is required

In the Context.Provider component, you’re passing a value prop that contains the data you want to share with all the components consuming the context. The reason for using two curly braces is that:

  1. The first set of curly braces is part of JSX syntax to embed a JavaScript expression inside JSX. Whenever you want to pass a JavaScript object or expression as a prop, you wrap it in curly braces.
  2. The second set of curly braces represents the actual object that you’re passing as the value. In your case, you’re passing an object with a key , which might look something like { a: someValue }.

Step 3 – Consume the context

  • Imported out “ThemeContext” and “useContext” hook.
  • Destructor the data
  • Use it anywhere

A.jsx

import React, { useContext } from "react";
import { ThemeContext } from "../contexts/ThemeContext";

const A = () => {
  const { text, setText } = useContext(ThemeContext);

  return (
    <div>
      <h1>{text}</h1>
      <button onClick={() => setText("Hello, world!")}>Click me</button>
    </div>
  );
};

export default A;

Step 4 – Optimizing with custom hook

src/contexts/ThemeProvider.js

import { createContext, useState } from "react";

export const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [text, setText] = useState("");
  return (
    <ThemeContext.Provider value={{ text, setText }}>
      {children}
    </ThemeContext.Provider>
  );
};

App.jsx

import { ThemeProvider } from "./contexts/ThemeContext";

function App() {
  return (
    <ThemeProvider>
      <A />
      <B />
    </ThemeProvider>
  );
}

export default App;

Benifits of using Context API

he Context API offers several benefits for managing state and avoiding prop drilling in React applications:

  1. Avoid Prop Drilling: It eliminates the need to pass props through multiple layers of components, simplifying your component tree and reducing boilerplate code.
  2. Centralized State Management: Provides a way to manage and share state or data globally across components, which can be useful for themes, user authentication, or global settings.
  3. Improved Code Readability: Reduces the complexity of passing data through many intermediary components, making the code easier to read and maintain.
  4. Component Decoupling: Helps in decoupling components that are not directly related but need to share common data, making components more modular and reusable.
  5. Flexibility: You can use multiple contexts to manage different pieces of state or data, offering a flexible approach to component communication.
  6. Reduced Prop Passing: Simplifies component interfaces by removing the need to pass props through intermediate components that don’t need to use them.

Overall, the Context API can lead to cleaner, more maintainable code by centralizing state management and avoiding cumbersome prop drilling.

Conclusion

React’s Context API allows you to create a context that can be provided at a higher level in the component tree and consumed by any descendant component, avoiding the need to pass props through every intermediate component.

Help Others

Leave a Reply

Your email address will not be published. Required fields are marked *