How to access localStorage before page renders
Answered
Jesse677 posted this in #help-forum
Jesse677OP
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.
Are there any persistent stores which can be accessed before the page renders.
7 Replies
@Jesse677 you can wait till localStorage is defined before you show the content
Jesse677OP
Yeah, I saw something about that online but I want to see if there's any other solution
Jesse677OP
apparently I could use cookies and SSR
Answer
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)));
}
}
...
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
Jesse677OP
Yeah, got it all to work now, thanks!