How to use Context API with React Router v4?

Sometimes, we want to use Context API with React Router v4.

In this article, we’ll look at how to use Context API with React Router v4.

How to use Context API with React Router v4?

To use Context API with React Router v4, we wrap the Context.Provider component around our route components.

For instance, we write

Store.js

import React, { createContext, useReducer } from "react";
import Reducer from "./reducer.js";

const initialState = {
  //...
};

const Store = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, initialState);

  return (
    <Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
  );
};

export const Context = createContext(initialState);
export default Store;

to define the Store component that wraps the Context.Provider around the children prop.

children has the components that we put inside Store.

Then in App.js, we write

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route
          exact
          path="/"
          render={(props) => (
            <Store>
              <Home {...props} />
            </Store>
          )}
        />
        <Route
          exact
          path="/about"
          render={(props) => (
            <Store>
              <About {...props} />
            </Store>
          )}
        />
        <Route
          exact
          path="/login"
          render={(props) => (
            <Store>
              <Login {...props} />
            </Store>
          )}
        />
      </Switch>
    </BrowserRouter>
  );
};

to set the render prop of each Route component to a function that renders Store with the route component inside.

As a result, Home, About, and Store has access to the Context we defined in Store.js.

Conclusion

To use Context API with React Router v4, we wrap the Context.Provider component around our route components.