How to easily use context provider in Next.js

Cover Image for How to easily use context provider in Next.js
Ali Bentaleb

In this tutorial, we are going to present easy steps on how to use react context provider in next.js

The steps are:

  • Create context component
  • Edit app.js file to make context provider available for all Next.js pages
  • Set context from any component in your app
  • Get context value from any component in your app

let’s start and see step by step how to do it:

Create context component

First, we create react context using react createContext and export it

Name the file /components/AppContext.js

Its content is :

import {createContext} from 'react';

const AppContext = createContext();

export default AppContext;

Edit _app.js

Next, let’s edit _app.js so that for every page, the context will be accessible

In /pages/_app.js

import '../styles/globals.css';
import {useState} from 'react';
import AppContext from '../components/AppContext';

function MyApp({Component, pageProps}) {
	const [session, setSession] = useState();

	return (
		<AppContext.Provider value={{session, setSession}}>
			<Component {...pageProps} />
		</AppContext.Provider>
	);
}
export default MyApp;

With this, every page has access to session state variable, and can overwrite it too with the setSession method.

Set context from a component

Now, from any page of our app, we can either set or read context

let’s set context from a page

On /pages/page1.js

import AppContext from '../components/AppContext';
import {useContext} from 'react';
import Link from 'next/link';

export default function Page1() {
	const context = useContext(AppContext);

	return (
		<div className="flex flex-col p-2 gap-2 w-1/4">
			<input
				className="border-2 h-12  p-2"
				placeholder="Value to put in react context"
				onChange={(e) => context.setSession(e.target.value)}
			></input>

			<Link href="/page2">
				<a className="hover:underline text-blue-400">
					Navigate to page2
				</a>
			</Link>
		</div>
	);
}

What the user has typed in the given input is set on react context, then when you click on the link page2, it will you take you to /page2

Now , all what we have to do is to build page2 to read context. Let’s see how we can build it

On /pages/page2.js

import {useContext} from 'react';
import AppContext from '../components/AppContext';

export default function Page2() {
	const context = useContext(AppContext);
	return <div>{context.session}</div>;
}

This page is reading the value that has been set in the context, in our case it is page1 who has set the context for us

Testing

Now, let’s test what we have done, run your app and browse to _localhost:3000/page1

Put some context in the input like the following use context in nextjs to share state page 1

Now click on the link, you should be able to see the context that have you typed like the below:

use context to share state

Conclusion

We have seen how to use react context provider to share state between components in Next.js

React context is very helpful in big apps to share data across pages and components, but keep in mind that it will be erased once you refresh the browser

Finally If you need only some few variables, i recommend to use Next.js router capabilities to share data between pages, check this article to learn how. It is more easy and convenient for small apps.

How to easily change basePath ...How to easily copy text to cli...