Next.js Discord

Discord Forum

How to access localStorage before page renders

Answered
Jesse677 posted this in #help-forum
Open in Discord
Avatar
I want to access the theme value in localStorage before the page renders so that I can render the content appropiately, however I'm seeing a few second delay when I use it in a useEffect, however when I try to put it in the component body directly, as shown in the attached file. I receive a build error saying localStorage isn't defined.

Are there any persistent stores which can be accessed before the page renders.
Image
Answered by Jesse677
apparently I could use cookies and SSR
View full answer

7 Replies

Avatar
@Jesse677 you can wait till localStorage is defined before you show the content
Avatar
Yeah, I saw something about that online but I want to see if there's any other solution
Avatar
apparently I could use cookies and SSR
Answer
Avatar
Giant Angora
If you require SSR you cannot get a value from localStorage for the server html easily
without it being in the html you'll get hydration errors if you try to do something like this

export function Component() {
  const [storedValue, setStoredValue] = useState(null);
  
  if (typeof window !== "undefined" && storedValue === null) {
    const value = window.localStorage.getItem("value");
    if (value) {
      flushSync(() => setStoredValue(parseInt(value)));
    }
  }
...
Avatar
yea use cookies, localStorage is a client thing, so until the page loads first, then react hydrates the page, then it finally gets the data from localStorage you wont see anything
Avatar
Yeah, got it all to work now, thanks!