Next.Js React Context Tutorial - How to use context api with nextjs


Posted 3 years ago by Ryan Dhungel

Category: React Hooks Next JS

Viewed 49750 times

Estimated read time: 12 seconds

Take the following steps to implement context in your nextjs project

Here I will also show you how to combine multiple context

 

  • In the root directory of your project, create a folder called context
  • Create index.js inside context folder
  • Put the following code in index.js

    import { useState, useEffect, useReducer, createContext } from "react";
    import { user } from "./reducers/user";
    
    // initial state
    const initialState = {
      user: {},
    };
    
    // create context
    const Context = createContext({});
    
    // combine reducer function
    const combineReducers = (...reducers) => (state, action) => {
      for (let i = 0; i < reducers.length; i++) state = reducers[i](state, action);
      return state;
    };
    
    // context provider
    const Provider = ({ children }) => {
      const [state, dispatch] = useReducer(combineReducers(user), initialState); // pass more reducers combineReducers(user, blogs, products)
      const value = { state, dispatch };
    
      return <Context.Provider value={value}>{children}</Context.Provider>;
    };
    
    export { Context, Provider };
    ​
  • Inside context folder, create another folder called reducers
  • Inside reducers folder, create user.js
  • Put the following code in user.js

    export function user(state, action) {
      switch (action.type) {
        case "LOGGED_IN_USER":
          return { ...state, user: action.payload };
        default:
          return state;
      }
    }
    ​
  • Now we are ready to use context
  • Create a pages folder in the root directory
  • Create a file called _app.js in pages folder
  • Put the following code. You may need to restart your server after this one

    import App from "next/app";
    import { Provider } from "../context";
    
    class MyApp extends App {
      render() {
        const { Component, pageProps } = this.props;
        return (
          <Provider>
            <Component {...pageProps} />
          </Provider>
        );
      }
    }
    
    export default MyApp;
    ​
  • Now finally you can try updating context state
  • Put the following code in pages/index.js and give it a try

  • import React, { useState, useContext } from "react";
    import { Context } from "../context";
    
    const Index = () => {
      const { state, dispatch } = useContext(Context);
      return (
        <div>
          <p>index page</p>
          <button
            onClick={() =>
              dispatch({
                type: "LOGGED_IN_USER",
                payload: "Ryan Dhungel",
              })
            }
          >
            login
          </button>
          <button
            onClick={() =>
              dispatch({
                type: "LOGGED_IN_USER",
                payload: null,
              })
            }
          >
            logout
          </button>
          {JSON.stringify(state)}
        </div>
      );
    };
    
    export default Index;