Blog>
Snippets

Persisting State with Context API

Code snippet that uses the React Context API to persist state across different components in the Next.js application.
import React, { createContext, useContext, useReducer } from 'react';

// Define the context
const StateContext = createContext();
First, we import React and necessary hooks, then define the context using createContext.
const initialState = { /* initial state values */ };

function stateReducer(state, action) {
  switch (action.type) {
    // Handle different actions
    default:
      throw new Error(`Unhandled action type: ${action.type}`);
  }
}
We define the initial state and the reducer which will handle the state changes based on dispatched actions.
export const StateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(stateReducer, initialState);

  // The value prop is where we provide the state and dispatch function to the context
  return (
    <StateContext.Provider value={{ state, dispatch }}>
      {children}
    </StateContext.Provider>
  );
};
This component provides the context to its children. We use the useReducer hook to get the state and dispatch function and pass it down through the context.
export const useStateValue = () => useContext(StateContext);
Using this custom hook, components can easily access the state and dispatch function.
import { StateProvider, useStateValue } from './stateContext'; // assuming stateContext is the file we created above

// Wrap your Next.js app with StateProvider
function MyApp({ Component, pageProps }) {
  return (
    <StateProvider>
      <Component {...pageProps} />
    </StateProvider>
  );
}

export default MyApp;
In the main app component, we wrap the entire app with the StateProvider so that state and dispatch can be accessed from anywhere within the app.
const SomeComponent = () => {
  const { state, dispatch } = useStateValue();

  // Use the context state and dispatch as needed
  return <div>{/* component code */}</div>;
};
In a component, we use useStateValue to access the state and dispatch function and then use these to manage or display the application state.