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

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();

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 };
  • 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;

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;

Voila!