DEV Community

OdunayoO
OdunayoO

Posted on

React Context API with hooks

What is Context API?

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Since release 16.3, React has had a stable version of Context API that can be used to easily share data across multiple components. It can be passed directly to the components that need it, thus preventing props drilling.

Check out the documentation on Context

Why use Context API?

Context is mainly used when you want simple state management. Context makes you avoid props drilling. In Context, you make the parent component a provider and define the child as a consumer that directly uses props from the parent rather than the passing of props through each child component that leads up to the component where it is needed

Basic example demonstrating usage

You can use context by:

  • Creating the context

First, create a new project with create-react-app.

npx create-react-app react-context-app 
Enter fullscreen mode Exit fullscreen mode

When the project is ready, we have to create a few files.

src/context/main.js
src/component/main.js

React Context is initialized with React.createContext top-level API

import React, { createContext } from 'react';

const AppContext = createContext();
Enter fullscreen mode Exit fullscreen mode

createContext is used to initialize the React Context. It creates the context object with the Provider and Consumer component. It takes in a default value which can only be used when a component does not have a matching Provider above its tree

  • Providing the value of the context to the application
// src/context/main.js
import React, { createContext, useState } from "react";

const AppContext = createContext();
const AppContextProvider = ({ children }) => {
  let [state, setState] = useState({
    name: "Jane Doe",
    age: 20
  });
  const incrementAge = () => {
    setState(prevState => ({
      ...prevState,
      age: state.age + 1
    }));
  };
  const decrementAge = () => {
    setState(prevState => ({
      ...prevState,
      age: state.age - 1
    }));
  };

  return (
    <AppContext.Provider value={{ state, incrementAge, decrementAge }}>
      {children}
    </AppContext.Provider>
  );
};

export { AppContext, AppContextProvider };
Enter fullscreen mode Exit fullscreen mode
  • consuming the value
// src/component/main.js

import React, { useContext } from "react";
import { AppContext } from "../context/main";

const AppComponent = () => {
  const { state, incrementAge, decrementAge } = useContext(AppContext);
  return (
    <>
      <div>My name is {state.name}</div>
      <div>my age is {state.age}</div>
      <button onClick={incrementAge}>+1</button>
      <button onClick={decrementAge}>-1</button>
    </>
  );
};
export default AppComponent;
Enter fullscreen mode Exit fullscreen mode

In your App.js add the Provider to the app by wrapping it around the AppComponent

// src/App.js

import React from "react";
import { AppContextProvider } from "./context/main";
import AppComponent from "./component/main";
function App() {
  return (
    <AppContextProvider>
      <AppComponent />
    </AppContextProvider>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Voila!

Top comments (6)

Collapse
 
deeola profile image
deeola

Thanks for sharing this. It was super helpful.

Collapse
 
tomiiide profile image
Tomide Oladipo

Oh wow, thanks a lot for this.

The article was very easy to understand, I'll try it in my project for sure.

Collapse
 
ihsanashi profile image
Ahmad Ihsan

this was super helpful as my states quickly got out of hand with a big form. Context + hooks is just so delightful to use.

Thank you! 😁

Collapse
 
chuxmykel profile image
Chukwudi Ngwobia

Nice and straight to the point. It eems hooks made the context API a lot easier to use because the last time I tried to use it, I didn't like what I saw. Thanks Odunayo

Collapse
 
mrahman96 profile image
Mizanur Rahman

Thanks a lot

Collapse
 
sbin0819 profile image
sbin

Thank you :)