How to Use Context API in a Next.js App

Technology is changing day by day. After the success story of the React.js library, developers are behind a React.js framework which is Next.js. Next.js helps to build production-ready web applications in record time. Popular companies like Netflix, Tiktok, Hulu, etc. are using Next.js already for web development. Here we are going to integrate Context API in a Next.js app for better state management.

What is Next.js?

Next.js is a React.js framework mainly created to build production-ready web applications.

Before knowing about Next.js, we should learn React.js first. React.js is a JavaScript library made for developing beautiful UIs. React.js is doing well in this field, and what is the importance of Next.js?

One of the best benefits of Next.js is server-side rendering, where it renders the JavaScript code from the server and returns the static HTML pages. This ensures more SEO benefits.

Next.js also provides features like Image optimization, file-system routing, typescript support, built-in sass support, fast-refresh, etc.

What is Context API?

Context API is a state management tool bundled with the React.js library itself.

In React, a website is build using components. A component may consist of states, and functions.

Sometimes, we need to pass these states and functions from one component to another.

We know that this can be done by passing states and functions as props from one component to another.

But if both of these are child components, then we need to pass these states and functions to the parent component first. Then from there, we can pass these to another child component.

This is ok for a small react app. But when things getting bigger, we need a state management tool to handle it.

Third-party tools like Redux, MobX, etc. are best to handle states for bigger apps. But for middle-scale apps, it is best to use Context API. Because tools like Redux will take more setup time.

I already wrote an article about integrating Context-API in a React App, and you can refer to it.

How to use Context-API in a Next.js App

Here, we are going to build a multi-language app using Next. Where all components require a languages field. Here passing the field as props is not a convenient method. So we are using the Context API.

The app we are going to build will works the same as below.

There is a Navigation bar at the top and it consists of a brand title “Next Context API”, an About link, a Contact link, and a dropdown to select languages.

Clicking the brand title will return the home page with “/” as the route, the About link will return the about page with “/about” as the route, Contact link will return the contact page with “/contact as the route”.

RouteCorresponding page
/Home page
/aboutAbout page
/contactContact page

The dropdown link at the right top will show two languages, English and Spanish, and selecting the link will change the language of the entire app.

The strings to replace each content is stored in a separate file and toggle according to the selected language.

Complete file structure of the project

The complete file structure of the app we have built in this project is shown below. This will help you to identify the files we are going to create in the upcoming steps.

So let’s start creating a new Next.js project with the name “next-context-api-example“.

Create a Next.js application

First, we need to create a Next.js application using the NPX tool. Don’t worry about NPX, because it’s a tool coming with NPM(Node Package Manager) 5.2+ onwards.

So, after a successful installation of Node.js, create a Next.js application using NPX.

npx create-next-app next-context-api-example

This command will create a react application with the project name next-context-api-example.

Now enter the project directory and start the app.

cd next-context-api-example
npm run dev

It will open up the Next application we have created in our browser window with the address https://localhost:3000.

If you need further assistance in this step, I wrote an article to install and set up a Next.js app on Windows 10.

We can open up the project with Visual Studio Code or any other code editor.

Integrate React-bootstrap

To get the basic styling, we can integrate the react-bootstrap package with our app.

Install react-bootstrap and bootstrap packages first.

npm install react-bootstrap@next bootstrap@5.1.0

Then import the bootstrap.min.css CSS file to the _app.js file.

import "bootstrap/dist/css/bootstrap.min.css";

Store language strings

First, we need to store all the language strings to display according to the change in language.

So for our app, create a file called languagesObject.js and store strings for English(en), and Spanish(es) languages.

// languageObject.js

let languagesObject = {
  en: {
    navbarAboutLink: "About",
    navbarContactLink: "Contact",
    homeTitle: "Home",
    homeContent: "Next.js is the React Framework for Production",
    aboutTitle: "About",
    aboutContent:
      "Next.js gives you the best developer experience with all the features you need for production",
    contactTitle: "Contact",
    emailLabel: "Email",
    phoneLabel: "Phone",
  },
  es: {
    navbarAboutLink: "Sobre",
    navbarContactLink: "Contacto",
    homeTitle: "Hogar",
    homeContent: "Next.js es el marco de React para la producción",
    aboutTitle: "Sobre",
    aboutContent:
      "Next.js le brinda la mejor experiencia de desarrollador con todas las funciones que necesita para la producción",
    contactTitle: "Contacto",
    emailLabel: "Correo electrónico",
    phoneLabel: "Teléfono",
  },
};

export default languagesObject;

Create a context

Create a file named AppContext.js and export the context named AppContext with createContext API.

// AppContext.js

import React from "react";

const AppContext = React.createContext();

export default AppContext;

Wrap the entire app inside the AppContext.Provider

To pass the state and functions via Context API, we need to wrap the entire app inside AppContext.Provider component where the AppContext is created by us in the previous step.

In a Next.js app, we can see file _app.js inside the pages directory and, all the pages are rendered via this component.

Here, we will import the AppContext file and languageObject we created earlier. Then wrap the entire app with AppContext.Provider and pass the languageObject to the context API as the state.

Here we also declare a state variable languageSelected with a default value “en”. This default value will be used to render the English language contents as default.

We need the languageSelected and setLanguageStateSelected for the Navigation component. From there, the language is selected from a dropdown.

// pages/_app.js

import "bootstrap/dist/css/bootstrap.min.css";
import "../styles/globals.css";
import { useState } from "react";
import AppContext from "../AppContext";
import languagesObject from "../languagesObject";

function MyApp({ Component, pageProps }) {
  const [languageSelected, setLanguageSelected] = useState("en");
  const languageObject = languagesObject;
  return (
    <AppContext.Provider
      value={{
        state: {
          languages: languageObject[languageSelected],
          languageSelected: languageSelected,
        },
        setLanguageSelected: setLanguageSelected,
      }}
    >
      <Component {...pageProps} />
    </AppContext.Provider>
  );
}

export default MyApp;

Create a Navigation Component

Now let us create a Navigation component inside the components directory that is common for all pages. Here, we are using the useContext API to get the states and functions passed from the _app.js file, that means via context API.

We are getting the languages as the value object. Also, the value.setLanguageSelected(“en”) and value.setLanguageSelected(“es”) will assign the values en, and es to the languageSelected state. This is used to set the exact language object from the languages from the _app.js file.

// components/Navigation.js

import { Navbar, Nav, Container, NavDropdown } from "react-bootstrap";
import Link from "next/link";
import { useContext } from "react";
import AppContext from "../AppContext";

export default function Navigation() {
  const value = useContext(AppContext);
  let { languageSelected } = value.state;
  let { navbarAboutLink, navbarContactLink } = value.state.languages;

  return (
    <Navbar collapseOnSelect expand="lg" bg="light" variant="light">
      <Container>
        <Link href="/">
          <a className="navbar-brand">Next Context API</a>
        </Link>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
          <Nav className="me-auto"></Nav>
          <Nav>
            <Link href="/about">
              <a className="nav-link">{navbarAboutLink}</a>
            </Link>
            <Link href="/contact">
              <a className="nav-link">{navbarContactLink}</a>
            </Link>
            <NavDropdown
              title={languageSelected.toUpperCase()}
              id="collasible-nav-dropdown"
            >
              <NavDropdown.Item onClick={() => value.setLanguageSelected("en")}>
                English
              </NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item onClick={() => value.setLanguageSelected("es")}>
                Spanish
              </NavDropdown.Item>
            </NavDropdown>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>
  );
}

Create Home page

Inside the pages directory, we can now create each page. So first create an index.js file for rendering the home page. By default, the home page will be rendered, and clicking the brand link will also render the home page.

The languages state from context API is imported into all pages to get the selected language strings.

// pages/index.js

import { useContext } from "react";
import AppContext from "../AppContext";

import { Container } from "react-bootstrap";
import Navigation from "../components/Navigation";

export default function Home() {
  const value = useContext(AppContext);
  let { homeTitle, homeContent } = value.state.languages;

  return (
    <>
      <Navigation />
      <Container className="page">
        <h2>{homeTitle}</h2>
        <p>{homeContent}</p>
      </Container>
    </>
  );
}

Create an about Page

In the same manner, create an About page to render the about view. Clicking the About link will render this page with a route “/about”.

// pages/about.js

import { useContext } from "react";
import AppContext from "../AppContext";

import { Container } from "react-bootstrap";
import Navigation from "../components/Navigation";

export default function About() {
  const value = useContext(AppContext);
  let { aboutTitle, aboutContent } = value.state.languages;

  return (
    <>
      <Navigation />
      <Container className="page">
        <h2>{aboutTitle}</h2>
        <p>{aboutContent}</p>
      </Container>
    </>
  );
}

Create a contact page

Now we can set up a contact page for the route “/contact”. This page will be rendered when the Contact link is clicked from the Navigation component.

// pages/contact.js

import { useContext } from "react";
import AppContext from "../AppContext";
import { Container } from "react-bootstrap";
import Navigation from "../components/Navigation";

export default function About() {
  const value = useContext(AppContext);
  let { emailLabel, phoneLabel } = value.state.languages;

  return (
    <>
      <Navigation />
      <Container className="page">
        <h2>{value.state.languages.contactTitle}</h2>
        <div>
          <li>{`${emailLabel}: hi@example.com`}</li>
          <li>{`${phoneLabel}: +010112345`}</li>
        </div>
      </Container>
    </>
  );
}

Add some global style(Optional)

We added a global style in the _app.js file. So we need to create the file. This style is common for the entire app.

// styles/globals.css

.page {
  margin-top: 5rem;
}
h2 {
  font-size: 50px;
}
p {
  font-size: 15px;
}

Codesandbox

Refer to the CodeSandbox link to view the live app. You can clone this project to your CodeSandbox account and edit the code also.

https://codesandbox.io/s/nifty-kare-106mr

GitHub

You can always refer to the GitHub repository to clone this project, refer to the code and work on top of it.

https://github.com/syamjayaraj/next-context-api-example

Summary

So in this article, we learned the benefits of Next.js, What is Context API, and how to use context API in a Next.js app. We created a multi-language Next.js app with Context API. Each step is explained well and the GitHub repository is added for reference. CodeSandbox link is also given to see the working demo of the project we created.

One thought on “How to Use Context API in a Next.js App

  1. Very good content but Can I use different folder for Context API like in src/view Folder . Is it necessary to declare in _app.js file

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.