Using React Context for state management in Next.js

Cassidy Williams - Dec 2 '20 - - Dev Community

Happy Blogvent season, devs!

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!

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Woo hoo!

If you want to see this in action in a real application, you can check out the open sourced repo for Jamstack Explorers!

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player