React Context API:  A Lightweight Alternative to Redux

R

The Context provides a path to pass data through the component tree without passing props down manually at every component.

Context API (React API) solves a lot of problems that modern applications face due to state management and how they’re passing state to the components. Instead of installing a state management library in your project which will cost our project performance and increase our bundle size, we can easily go with Context API and be fine with it.

Why Context API?

Context API is the concept of React which break our application into components, for reusability purposes. So in a simple React application, we have a few different components. As our application grows, the components can become very huge and we are not able to maintain them, so we break them into smaller components. We use Context API to share data with multiple components, without passing data through props manually. For example, in some use cases, Context API is ideal for theming, user language, authentication, etc.

createContext()

Before we start with Context API, the first thing we need is to create a context using the createContext function from React.

const NotesContext = createContext([]);

After creating the context, the context now has two React components, the first one is Provider and the Second one is Consumer.

Provider

Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. A single Provider can be connected to one or many consumers. Providers can also be nested to override values deep within the tree.

<NotesContext.Provider value={this.state.notes}>

</Notes.Provider>

Consumer

The consumer requires a child to function. The function receives the current context value and returns React node. The value argument passed to the function will be equal to the value prop of the closest Provider for the context above in the tree. If there is no Provider for the context above, the value argument will be equal to the defaultValue that was passed to createContext().

<NotesContext.Consumer>

  {values => <h1>{value</h1>}

</Notes.Consumer>

useContext

React Hooks allow us to manage state data inside functional components; now we do not need to create a class component just to manage state data.

React has a few built-in hooks for ex. useStateuseCallbackuseEffect, etc. The one which we’re going to talk and learn more about is the useContext hook.

 The useContext hook allow to connect and consume a context. The useContext hook receives a single argument, which is the context that we want to have access to.

const notes = useContext(NotesContext);

We have to create a file called context.js. Inside the context.js file, we have to create context and provider, import the useState hook and useContext hook from React at the top, and we have to create a context which is going to be called as AuthContext. The initial value of the AuthContext will be undefined for now.

import React, { useState, useContext } from “react”;

const AuthContext = React.createContext(undefined);

Now, we have to create a functional component called AuthProvider, which will receive children as props. Inside this component, we’re going to render more components and handle the state data which we want to share with the other components.

const AuthProvider = ({ children }) => {        };   

Example:

import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";

const UserContext = createContext();

function Component1() {
  const [user, setUser] = useState("Jesse Hall");

  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 />
    </UserContext.Provider>
  );
}

function Component2() {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 />
    </>
  );
}

function Component3() {
  return (
    <>
      <h1>Component 3</h1>
      <Component4 />
    </>
  );
}

function Component4() {
  return (
    <>
      <h1>Component 4</h1>
      <Component5 />
    </>
  );
}

function Component5() {
  const user = useContext(UserContext);

  return (
    <>
      <h1>Component 5</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);

For all intents and purposes:

The Context API is a component structure provided by the React framework, which enables us to share specific forms of data across all levels of the application. It’s aimed at solving the problem of prop drilling.

About the author

Sanket Lamkhade
By Sanket Lamkhade

Category