I am using Next.js 14 with the app router. I have two routes, /businesses
and /people
. Both have a top-level React Server Component Page
which fetches the respective list data for each page. Each Page
then renders a client side component Content
, which takes the list data and hydrates a React Context for that page with the data, called DataContext
with its respective provider DataProvider
.
// app/people/page.tsx
const Page = () => {
const people = getPeople();
return <Content entities={people} />;
};
// app/people/content.tsx
const Content = ({ entities }) => {
const sortAndFilter = useSortAndFilter();
const { filters, pagination, sort } = sortAndFilter;
const searchableFields = ['name', 'role', 'businessName'];
const data = useFilteredEntities({ filters, pagination, sort, entities, searchableFields })
return (
<SortAndFilterProvider value={sortAndFilter}>
<DataProvider value={data}>
<SearchPage />
</DataProvider>
</SortAndFilterProvider>
)
};
I have verified the default 30 second client side Router Cache works by both logging on the server and looking at the network tab when moving between routes.
It appears that the React Context is being destroyed and re-created when navigating back to /people
, as the list momentarily flashes in an empty state when navigating back to this page. This happens even though the page itself appears to be fully cached on the client side. I am wondering if it is possible to keep the React Context alive inside of the Router Cache somehow?
2
Answers
Define a context file outside:
Wrap the app with the provider created:
Now, we can access the context state in the components: