Guides & Tutorials

Using React Context for state management in Next.js

Guides & Tutorials

Using React Context for state management in Next.js

There are a lot of different ways to manage state in Next.js applications, and many of these require installing something new. If you'd like to manage state across your Next.js applications, the easiest way to do it (without installing anything extra) is using React Context!

Context lets us pass data through the component tree without having to pass props down manually at every level.

If you'd like to use Context across every page in your application, you'll want to go to pages/_app.js and make it look a little something like this:

// src/pages/_app.js

function Application({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default Application

Then, make a file somewhere in your application that builds a Context object:

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

const AppContext = createContext();

export function AppWrapper({ children }) {
  let sharedState = {/* whatever you want */}

  return (
    <AppContext.Provider value={sharedState}>
      {children}
    </AppContext.Provider>
  );
}

export function useAppContext() {
  return useContext(AppContext);
}

Once this is done, go back to pages/_app.js and wrap your component with the AppWrapper:

// src/pages/_app.js
+ import { AppWrapper } from '../context/AppContext'; // import based on where you put it

export default function Application({ Component, pageProps }) {
  return (
+    <AppWrapper>
      <Component {...pageProps} />
+    </AppWrapper>
  )
}

export default Application

Now, in every component and page in your application, if you'd like to access the values inside of that sharedState object, you can import and call the React useAppContext hook!

Now, be discerning about how much you put into Context. You wouldn't want unnecessary re-renders across pages when you can just share them across certain components.

React Context for state management example

If you want to see this in action in a real application, you can check out the open sourced repo for the [Jamstack Explorers] (https://www.youtube.com/c/NetlifyApp/playlists) site.

Here is the code for _app.js, and here is the folder that uses React Context for the different providers created!

Keep reading

Recent posts

Book cover with the title Deliver web project 10 times faster with Jamstack enterprise

Deliver web projects 10× faster

Get the whitepaper