DEV Community

Cover image for Beginner's Journey into React's Context API
Mr Emma
Mr Emma

Posted on

Beginner's Journey into React's Context API

Beginner's Journey into React's Context API

The Context API in React is a powerful tool that helps developers manage the state of their React applications. It provides a way to avoid the hassle and frustration of passing props down from parent components to deeply nested child components.

Imagine you have a counter-state that needs to be accessed by a component deep down in the component structure. Instead of creating the state in the parent component and passing it down as props, you can use the Context API to simplify state management and avoid what is called "state lifting".

State lifting in React refers to the process of moving the state of a component higher up in the component hierarchy, allowing multiple components to access and manipulate that state. It involves passing the state and relevant state update functions through props from a parent component to its child components.

In this blog post, we will walk through a simple example of how to use the Context API to manage a counter-state.

Image description

A Guide to React Context and useContext() Hook

Creating the Context

The first step is to create the context. This is done by creating a new file in our project's src folder and giving it a meaningful name, such as CounterContext.jsx. This file will be responsible for managing our counter state using the Context API.

In the CounterContext.jsx file, we need to import React, useState, and createContext from the React library. createContext is an inbuilt function in React that helps us create and manage state with the Context API.

We can then export the created context using export const CounterContext = createContext();. This sets up the context that will hold our counter state.

Here's an example code snippet for the CounterContext.jsx file:

import React, { useState, createContext } from 'react';

export const CounterContext = createContext();

Enter fullscreen mode Exit fullscreen mode

Creating the Provider

Next, we need to create a provider component for the context. This is the component that will expose the counter state to our other components.

The provider component takes a single prop, children, which is the component that will be rendered inside the provider. The provider component returns a element with the counter state as the value prop.

Here is an example code snippet for the provider component:

export const CounterProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  return (
    <CounterContext.Provider value={{ count, setCount }}>
      {children}
    </CounterContext.Provider>
  );
};

Enter fullscreen mode Exit fullscreen mode

In the provider component, notice that we are using the children prop. Instead of passing in specific components that need access to the state, we use the children prop. This simplifies our code and makes it more readable.

In the main entry point of your project, whether it's index.js or App.jsx, import the CounterProvider from the CounterContext file. Wrap your App component (or the root component of your application) with the CounterProvider component.

Here's an example code snippet for the main entry point:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { CounterProvider } from './CounterContext';

ReactDOM.render(
  <CounterProvider>
    <App />
  </CounterProvider>,
  document.getElementById('root')
);

Enter fullscreen mode Exit fullscreen mode

Using the Context

Now that we have created the context and the provider, we can use the context in our other components.

To use the context, we need to import useContext from React and the CounterContext from the CounterContext.jsx file. We can then use useContext(CounterContext) to access the counter state and state updater function.

Here is an example code snippet for using the context in a component:

import React, { useContext } from 'react';
import { CounterContext } from './CounterContext';

const CounterComponent = () => {
  const { count, setCount } = useContext(CounterContext);

  // Use the count state and setCount function as needed

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

CONCLUSION

That's it! Now we can manipulate the counter state in our component using the traditional approach, and everything will work seamlessly.

I hope this blog post has helped you to understand how to use the Context API in React. If you have any questions, please feel free to ask.

Top comments (0)