Simple Global State Management in Next.js

11.28.2020

There are times when you are working on a small project and you need a way to store some global state, such as the current user or theme.

Using a dedicated state management library like redux or mobx might be overkill.

Here is a simple way that I have found to manage global state without additional third party packages.

Step 1. Define a global-context object with the global variables.

./utils/global-context.js

import React from 'react';

const GlobalContext = React.createContext({
  count: 0,
  update: (data) => {}
})

export default GlobalContext

Step 2. Wrap the global context around the app component.

./pages/_app.js

import '../styles/globals.css';
import { useState } from 'react';
import GlobalContext from '../utils/global-context';

function MyApp({ Component, pageProps }) {
  const [state, setState] = useState({
    count: 0,
    update
  })

  function update(data) {
    setState(Object.assign({}, state, data));
  }

  return (
    <GlobalContext.Provider value={state}>
      <Component {...pageProps} />
    </GlobalContext.Provider>
  )
}

export default MyApp

Step 3. Use the global context in any of your pages or components.

./pages/index.js

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useContext } from 'react'
import GlobalContext from '../utils/global-context'

export default function Home() {
  const global = useContext(GlobalContext)

  function handleClick() {
    global.update({
      count: global.count + 1
    })
  }

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <p>{global.count}</p>
        <button onClick={handleClick}>Submit</button>
      </main>
    </div>
  )
}

The update function provides a convenient way to update any of the global properties from anywhere in your application.

GitHub Repo: https://github.com/travisluong/simple-global-state-example