2

I'm working with NextJS, I'm using context and useEffect to keep track of login session. I'm noticing that when I navigate from a page to another existing page (ex: Home -> About), Next doesn't re-compile my pages and only does a client-side routing, so my context is preserved and it's useEffect is not triggered, but when I navigate to a 404 page, the 404 page is being re-compiled by server everytime, so the state of the context goes briefly on the default state before triggering the useEffect to update it. Is there a way to avoid re-compiling on 404 page? Like doing it client-side to preserve context?

Looking around the internet I didn't find anything about how the pages and the 404 page are compiled, so: do you have some resources to look at to understand better how NextJS pages and error pages routing and compiling works?

Also, do you know if there's a way to avoid re-compiling the 404 page everytime, to avoid that initial default state?

I reproduced the error in a CodeSandbox snippet: Basically I have a ContextProvider in /context/context.js, in the context I have a useEffect that modifies the context state, delayed by 1sec, so you can appreciate my problem). After the page is loaded and 1sec passed, my context "id" is set to 10, if you navigate from "Index" to "AnotherExistingPage", the context is being preserved, because the routing is client-side, when you navigate to "404 page" (that's simply rendering the same thing as the other two pages), the context is reset and the useEffect is triggered again).

As a solution for avoiding this "state loading" I thought about using SSR to fetch the login status before serving the page, but I still want to know why 404 routing triggers a full website reloading instead of a client-side routing.

mvkv
  • 41
  • 3
  • Your repo is read only. Why dont you use useRouter of nextjs? – illia chill Dec 05 '22 at 14:53
  • @illiachill You can fork it if you want to play around, because I need to keep mine clean to let people see the problem. By the way, my problem is with the 404 redirecting from a non-existing page, so I can't use useRouter, I want to prevent redirecting to 404 triggering re-compiling of the whole SPA. – mvkv Dec 09 '22 at 13:48

0 Answers0