Skip to main content

Command Palette

Search for a command to run...

How to Use React's Context API for State Management

Published
6 min read
How to Use React's Context API for State Management
R

I'm a passionate frontend developer with a knack for crafting immersive user experiences. Over the years, I've honed my skills in ReactJS, MongoDB, Redux, React-Toolkit, and SQL, leveraging these tools to deliver robust and dynamic web applications. I am passionate about explore and learning new things and willing to work beyond my capacity to administer projects. 💼 Currently, Diving deep into MEAN stack

Hey folks, Let's dive deep into the concept of ContextAPI.

Why do we need this

When you create an application, managing state is an essential concept in React. A common way to manage state is by passing props, which means sending data from one component to another. But what if you want to use it in nested components?

Here, if you want to use props in the Card.jsx component, you need to pass the props through all the parent components of Card.jsx. This way, you can successfully use that information in your components 😊. Passing Props into the Components is also known as Props Drilling.

Ahh 😒, but there is a Problem in Props Drilling. I know you already figure it out. But for the Confirmation let me tell you. While sending data from Home to Card, Need of that data is only in Card Component, But passing props down a chain of multiple components to reach a specific component can make your code overly cumbersome.
Illustration of passing props from parent to children.

In the diagram above, to pass data to the "Main.jsx" component, we have to send it through all the intermediate components, even if those components don't use the data😒. This process is known as "prop drilling."

Prop drilling can make your code harder to read and maintain, and it can also complicate refactoring your components later.

This is where the Context API comes in. With the Context API, you can store data at the top level of the component tree and make it available to all other components that need it, without having to pass props through each level.

There are more other tools that use to manage the state in React.

  • Context API

  • React-Redux

  • Zustand

  • Flux

  • mobX

We will talk about these Tools later, Let’s Focus on ContextAPI.

What is context API

Basically, Context API is a feature in React, a popular JavaScript library for building user interfaces, that enables sharing data across components without having to pass props down manually at every level. It is particularly useful for managing state that needs to be accessed by multiple components in a React application, such as themes, authentication status, or user preferences.
Key Features of Context API:

  1. Global State Management: It allows you to create global variables that can be shared across the component tree.

  2. Efficient Prop Drilling Elimination: It helps to avoid "prop drilling," where props need to be passed down multiple levels in a component hierarchy.

  3. Easy to Implement: It is part of React itself, so there’s no need for additional libraries like Redux for smaller state management needs.

How the Context API Works

The Context API lets you pass data through a component tree without manually passing props at each level. This simplifies sharing data between components.

A diagram illustrating how Context API works

For Example, Let’s Say you have a Authentication App with a components that show data only when you are LoggedIn otherwise it say “Please Login”. And the Navbar that shows Logout button if you are loggedIn otherwise it Shows Login, Register Button.
With Context API you can create “Context“ that hold the login information, then you can you that information directly in you Authentic component and Navbar,without having to pass the information down through props.

It’s like having a Global box that holds all the things you need for your Authentication. You can take things out of the box when you need them, and put them back in when you’re done.

Basically, the Context API consists of two main parts: the context provider and the context consumer. The provider creates and manages the context, which contains the data to be shared between components. The consumer, on the other hand, is used to access the context and its data within a component.

In the example given, the provider will create the context that holds the user's login information, while the consumer components (Login, Dashboard, Navbar, Profile) will access that context to retrieve the data they need. This avoids the need to pass the information down through props, making your code more efficient and easier to manage.

Implement in Code

First create a seperate file in the root of the Project folder, And named it store.jsx (you can named it anything that you want but store name is convinient).

I choose to keep it inside the store folder.

  1. Create a Context

Then just import createConext method from react and store it in a variable, i named that variable authContext

import { createContext } from "react";

export const AuthContext= createContext();
  1. Create a Provider Component

    Then create an arrow function and store it in a variable, i name that variable authProvider. and pass a paramenter object in authProvider. Now export both variable.

import { createContext } from "react";

export const AuthContext = createContext(); 
export const AuthProvider = ({ children }) => {
};

Inside the authProvider, return a component called Provider. The Provider isn't directly accessible; it's a feature provided by the createContext method. Since we stored the createContext method in the authContext variable, all its functionality is now within authContext. authContext is an object, and you can access its properties using dot notation. To use the Provider from authContext, you can write <authContext.Provider> </authContext.Provider>. Use the parameter inside the component and pass everything you want to be accessible throughout the application as props in the <authContext.Provider> component.

import { createContext } from "react";

export const AuthContext = createContext(); 
export const AuthProvider = ({ children }) => {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

      return (
        <AuthContext.Provider value={{ state, setState }}>
          {children}
        </AuthContext.Provider>
    );
};
  1. Wrap Your Application with the Provider

Use the provider at the top level (e.g., in App.jsx/main.jsx)
By wrapping your parent components with this context, it will be accessible to all the child files of that parent.

import App from './App.jsx'
import './index.css'
import { AuthProvider } from './store/store.jsx'

createRoot(document.getElementById('root')).render(
  <AuthProvider>
    <StrictMode>
      <App />
    </StrictMode>
  </AuthProvider>
)
  1. Consume the Context in Child Components

Use the useContext hook to access the context in functional components
In order to use the Context in a child component, we need to access it using the useContext Hook.
Then you can access the user Context in all components

import React, { useContext } from "react";
import AuthContext from "./store.jsx";

const MyComponent = () => {
  const { isLoggedIn, setIsLoggedIn } = useContext(AuthContext);

  return (
    <div>
      <p>Current State: {isLoggedIn}</p>
      <button onClick={() => setIsLoggedIn(true)}>Login</button>
    </div>
  );
};

export default MyComponent;

This setup allows you to manage global state in your React application using Context API. It's particularly useful for smaller-scale applications or specific feature-level state management. For larger apps, you might consider using state management libraries like Redux.

For thousands of users, the Context API is powerful enough to manage states.

How well do you think you’ve understood the Context API after reading this guide?

  • 🔍 Still unclear? Let me know which part needs more detail.

  • ✅ Fully understood? Share an example of how you plan to use it in your next project!

Happy Coding 😊🎉😊

🙏 Namaste 🙏

V

wonderful work, thanks for sharing.

1