Error when using server-side rendering (SSR)
See original GitHub issueOverview
This hook currently throws this error when used with ReactDOMServer
:
ReferenceError: window is not defined
at eval (webpack:///./node_modules/react-use-localstorage/dist/react-use-localstorage.esm.js?:12:5)
This happens because it’s trying to access localStorage
when getting the initial value (runpkg link):
Note: The function that is passed to useEffect
isn’t executed on a server, so accessing localStorage
there doesn’t cause any problems.
Expected Behaviour
The initialValue
is always used when rendering on the server.
Current Behaviour
It throws an error.
Workaround
An easy way to workaround this issue is to wrap it in a custom hook:
const useSSRLocalStorage = (key, initial) =>
typeof window !== "undefined" ? useLocalStorage(key, initial) : [initial];
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:10 (3 by maintainers)
Top Results From Across the Web
Handling runtime errors when server side rendering with Next.js
Since we're using React, we are aware of using error boundaries as React exposes getDerivedStateFromError or componentDidCatch lifecycle methods ...
Read more >Error when I make a server-side rendering - Stack Overflow
This error is pretty self-explanatory. The rendered HTML code that is sent from the server mismatches with the DOM that is rendered on...
Read more >React Server Side Rendering Errors
Hi,. I am using MDB React Pro v4.8.7. My team uses SSR for all of our websites but I have been getting errors...
Read more >Errors during SSR are rendered as "loading" #3897 - GitHub
Server side rendering happens in 2 phases, firstly getDataFromTree() populates a cache by fake rendering, then that cache is used to render on ......
Read more >Logging and error management best practices in SSR apps
Handle errors and log them gracefully in your next web app with these best practice guidelines with examples using Next.js and Nuxt.js.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Just leaving a quick drive-by comment to thank @haydn for the workaround for this issue. I’m using this hook in a Gatsby project where all components need to be SSR safe and it fixed my problem!
Here’s what I came up with to satisfy TypeScript’s complaints about the workaround:
const useSSRLocalStorage = (key, initial) => typeof window !== "undefined" ? useLocalStorage(key, initial) : [initial]; // eslint-disable-line react-hooks/rules-of-hooks
This code doesn’t work for Next.js ^ 10. Any way, I could not apply it although I really wanted to.