Simple Global State Management in Next.js


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.


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.


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

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

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

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

export default MyApp

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


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() {
      count: global.count + 1

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

      <main className={styles.main}>
        <button onClick={handleClick}>Submit</button>

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

GitHub Repo: