SimpleNext.js
useContext React hook : How to use React context in Next.js
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>
)
}