Sharing state between Next.js page navigations using React Contexts
- react@18.2.0
- next@14.0.0
This article has been updated for .
Ever built a Next.js app and found yourself frustrated when your state disappears as users navigate between pages? You're not alone. Whether it's a shopping cart that empties when users click around, or user preferences that reset on every page load, this is a common pain point in Next.js applications.
The good news? There's a straightforward solution using React Context. Let me show you how to keep your state alive across page navigations.
The Problem
In Next.js, each page navigation is like starting fresh - your state gets wiped clean. This becomes a real headache when you need to maintain things like shopping cart items, user preferences, form progress, or authentication state. Every time a user clicks a link, your carefully maintained state vanishes into thin air.
The Solution
React Context to the rescue! It's like creating a persistent memory for your app that survives page navigations. Here's how to implement it:
First, create your context provider:
Next, wrap your app with the provider in your root layout:
Now you can use your shared state anywhere in your app:
What You Need to Know
Remember that context providers must be Client Components. You'll need to add the directive at the top of your context files, and any component using the context must also be a Client Component. This is because React Context relies on hooks, which only work in Client Components.
The placement of your provider is crucial. By putting it in the root layout, you ensure your state is available throughout your entire application. Think of it as creating a global state container that wraps your entire app.
Your state will now survive page navigations, but keep in mind that it will reset on a full page refresh. If you need your state to persist even after a refresh, you'll want to consider using localStorage or sessionStorage for client-side persistence, or implement server-side state management using cookies or a database.
Watch Out For
You might run into a few common issues while implementing this. If you see the error "hooks can only be used in Client Components," simply add the directive to your context file. If you get a "context is undefined" error, double-check that your component is properly wrapped in the provider.
Remember that while your state will persist during navigation, it won't survive a full page refresh. If you need that kind of persistence, you'll need to implement a storage strategy that works for your specific use case.
That's it! You now have a way to share state between pages in your Next.js app. For more details, check out the official Next.js documentation.