#How to access localStorage before page renders

9 messages · Page 1 of 1 (latest)

ocean thistle
#

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.

cinder tideBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

rapid zodiac
#

@ocean thistle you can wait till localStorage is defined before you show the content

ocean thistle
#

Yeah, I saw something about that online but I want to see if there's any other solution

#

apparently I could use cookies and SSR

sharp mason
#

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)));
    }
  }
...
rapid zodiac
ocean thistle
#

Yeah, got it all to work now, thanks!