Context API for Next.js – Complete State Management Guide

Context API for Next.js – Complete State Management Guide

Next.js has several built-in hooks, making it a popular choice of framework for developers. Next.js hooks make the lives of a developer very easy while building an application. In this guide, we will be learning how to manage the state and context-API in our application using only hooks, without using any third-party library by building a simple application.

Introduction

We frequently encountered situations while developing Next.js applications where we needed variables and data that could be accessed from components or pages other than where they were initialized. For example, you may have noticed that after a user logged in to an application, he can access his profile from any page of the application. This functionality is achieved by managing our state globally. So let’s discuss a method to achieve this.

What is Context-API?

context-API is a way to make a global store in an application where we can store data and variables. The variables and data which are in the context can be accessed from any page or component without manually passing the props from the parent component to the child component.

Why use Context-API?

Although there are many ways to achieve this functionality in our application, context API has its own place and advantages. These are some of the benefits of using it over others.

  • If we do not use context API or any other library and simply pass props from parents to the child and then from this child to another child, it will become a very hectic and bad way to write code as the number of children and props increases.
  • Context API is very light and fast in comparison to other state management libraries like redux and recoil as it is inbuilt in Next.js.

Using the Context-API effectively

Let’s see how we can use context API in our Next.js application in the right way. Suppose a user is just logged in and we want to store the user information globally. First, create the Next.js application and then create a context folder in the root directory. Inside the context folder, create a user.js file. There are three main steps in creating the global store using context API and making the user information available globally.

Step 1: Creating the context

// context/user.js

import { createContext, useContext } from "react";
// Creating the user context
const UserContext = createContext();

// Making the function which will wrap the whole app using Context Provider
export default function AppStore({ children }) {
  
    const user= {
        id: 1,
        name: "John Doe",
        token:"3DJ39#DFLLDF58$LKDFO#O3N4OO"
    }

  return (
    <UserContext.Provider value={ {user} }>
      {children}
    </UserContext.Provider>
  );
}

// Make useUserContext Hook to easily use our context throughout the application
export function useUserContext() {
  return useContext(UserContext);
}
Code language: JavaScript (javascript)

For creating the context we use the createContext hook and for using it, we use the useContext hook. Now we have to create an AppStore function with children prop as it will enclose our main app. The AppStore function will return the context provider which will give access to the store to all the children passed. In the last part of our code, we will create a custom hook useUserContext so that we can easily use our context in other components and pages.

Step 2: Wrapping our app in Context

To make our store global, we have to wrap our main app inside our store in the _app.js file like that

// pages/_app.js

import '../styles/globals.css'
import AppStore from '../context/user'

function MyApp({ Component, pageProps }) {
  return (

    // Wrapping our app in AppStore
    <AppStore>
      <Component {...pageProps} />
    </AppStore>
  )
}

export default MyApp
Code language: JavaScript (javascript)

Step 3: Using the Context

Now as our store now becomes global we can use it simply by importing it using the useUserContext hook which we created in user.js. Let’s display the user data on our index page.

// pages/index.js

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useUserContext } from '../context/user'

export default function Home() {

  // Getting user object using useUserContext Hook
  const { user } = useUserContext();

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1>Context API Tutorial</h1>
        <p>Logged in User: <strong>{user.name}</strong></p>
        <p>User token: <strong>{user.token}</strong></p>
      </main>
    </div>
  )
}
Code language: JavaScript (javascript)

Browser window view

image

Conclusion

If we want an easy, fast, and lightweight store for our project, then context-API is the best choice. You can learn more about Next.js through this course. You can use this repository for the code reference given in this tutorial.

Sharing is caring

Did you like what Mohd Rashid wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far