SimpleNext.js

useContext React hook : How to use React context in Next.js

Cover Image for useContext React hook : How to use React context in Next.js
Marouane Reda
Marouane Reda
If you need to understand the basics of Next.js, i recommend this course. (Disclaimer : this is an affiliate link that may earn me a small commission, but with no extra cost to you if you choose to enroll)

Starting from React v16.3.0 , it is possible to use a new feature named context to pass data throughout the app. This approach can replace the tedious top-down passing of data through props and in some measure can also be used instead of Redux. Let’s see how we can use context in Next.js.

In this article, we will see how to use useContext hook for Next.js . It is possible to use directly Context, but useContext hook is simpler to use and provides the exact same functionalities

Create our app

create-next-app context-app

Create a context directory and state.js file under it

Here we will create a context named AppContext, then a wrapper AppWrapper that will be used later in every page and will provide ApContext to these pages :

import { createContext, useContext } from 'react';

const AppContext = createContext();

export function AppWrapper({ children }) {
  let sharedState = {/* whatever you want */
    value : 42
   
}
  

  return (
    <AppContext.Provider value={sharedState}>
      {children}
    </AppContext.Provider>
  );
}
export function useAppContext() {
  return useContext(AppContext);
}

Here we pass AppContext to useContext and use instead a new hook useAppContext, but it is essentially the same thing.

Modify _app.js file by adding the AppWrapper

if ./pages/_app.js isn’t already created, create it, then modify it like this ;

import { AppWrapper } from '../context/state';
const app = ({ Component, pageProps }) => {
  return (
    

      <AppWrapper>
      <Component {...pageProps} />
      </AppWrapper>
  
    
  )
}

export default app

_app.js is used to initialize every page in our app. By adding the AppWrapper to _app.js, we make the context accessible to all our pages.

Use useAppContext hook in our app

As easy as :

import { useAppContext } from '../context/state';
export default function Component() {
  
  const mycontext = useAppContext();
  console.log(mycontext)
  
  return (
    <div>
   <p> value is {mycontext.value} </p>
    </div>
  )
 

}

Final result

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-09-15%20a%CC%80%2016.46.50.png?alt=media&token=ef2651c2-94d4-452f-94ae-e040c0d9740a