Next.js Use localStorage For Rendering Without Flash?
Hello,
I am trying to grab data from localStorage and use it to change the text in a button. This system should detect if a user has clicked the button before and say "continue" instead of "start." I made a
useUserHistory
hook to wrap this behaviour.
Only this version results in no error, but it always flashes "Start" until the value is retrieved.
When I use
and remove the first useEffect
, it seems to work, but I do get a error for localStorage not being defined.
I understand this is due to the server pre-rendering the initial value of useState, a behaviour I do not want in this case.
Should I rethink this entire system?4 Replies
the component renders first on the server where you don't have the local storage
and the useeffect runs after the component is rendered the first time
you have to use cookies or something similar
There has to, or atleast should be, a way to do this completely client side. The server overhead for something so small is not really worth it.
if the little flash of "start" really bothers you, or you need to be 100% certain that the user doesn't click the button in the wrong state, render the button as hidden initially, and only update the visibility when the localStorage state. becomes available
Basically, you can't totally avoid the flash, because the SSR page will never have localStorage.
If the component is not the LCP element on the page, I'd just render null or a placeholder in the
component that renders it. E.g. using a mounted hack: