How to use React Context for state management in Next.js

Despite what your favourite developer on Twitter says, you don't always need redux for managing state in your React app. You already knew that and that's why you're here.

In this blogpost, I'll show you how to use React Context for state management in a Next.js application.

Why should I used React Context with Next.js?

If you want to manage state in your Next.js application, the easiest way to do so is using React Context. You won't need to install any additional dependencies since it's part of the core React library.

How to use React Context with Next.js

If you want to use Context on every page of your Next.js application, follow the guide below…

Step 1:
Create a new file for your Context. I suggest context/state.js. Within this file add the code to build your Context object. A boilerplate is shown below as an example:

// context/state.js
import { createContext, useContext } from 'react';

const MyContext = createContext();

export function MyProvider({ children }) {
    const value = {};
    
    return (
        <MyContext.Provider value={value}>
            {children}
        </MyContext.Provider>
    );
}

export function useMyContext() {
    return useContext(MyContext);
}

Step 2:
Now open the pages/_app.js file and wrap the default component with the MyProvider created in Step 1. It will look something like this:

// src/pages/_app.js
import { MyProvider } from '../context/state';

export default function MyApp({ Component, pageProps }) {
    return (
        <MyProvider>
            <Component {...pageProps} />
        </MyProvider>
    )
}

Step 3:
Now in every component and page of your Next.js application you can access the state shared in your Context using the custom useMyContext() hook created in Step 1.

That's all there is to it!

Subscribe to Email Updates