DEV Community

loading...
Netlify

Using React Context for state management in Next.js

cassidoo profile image Cassidy Williams Originally published at netlify.com Updated on ・2 min read

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!

Discussion (2)

pic
Editor guide
Collapse
georgemburu profile image
Georgemburu • Edited

Hello, you sure this will work?

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

Since you are using a hook outside a react component

OOOOWWW!!
Sorry my bad.

Was using the hook inside jsx while i should be using it inside the body of the component.

Thanks alot for the post

Collapse
cassidoo profile image
Cassidy Williams Author

Glad you got it :)