-
Notifications
You must be signed in to change notification settings - Fork 32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error when using server-side rendering (SSR) #24
Comments
Hi @haydn Thanks for the SSR issue and the workaround for it. I think the implementation of |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
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: string, initial: string): [string, React.Dispatch<string>] => {
return typeof window === 'undefined'
? [initial, (value: string) => undefined]
: useLocalStorage(key, initial)
} |
#34 to associate the issue. |
PLEASE PLEASE PLEASE reference this fix for Gastby users. I spent days trying to track down what was happening. @haydn and @hencatsmith (I use Typescript) fix was great for my Gastby build error! |
Hi @otherjohn. I've updated README with @hencatsmith's workaround |
Where exactly should you put this useSsr hook? I get the following error:
|
@AdityaAnand1 Ah, yes. That linter is probably upset that we're calling A workaround for now would be to disable the ESLint rule: const useSSRLocalStorage = (key, initial) =>
typeof window !== "undefined" ? useLocalStorage(key, initial) : [initial]; // eslint-disable-line react-hooks/rules-of-hooks @dance2die This might be a reason to solve the problem inside the hook instead of leaving it to users to workaround it. SSR is becoming a lot more common with things like Gatsby and Next.js rising in popularity, so I think you're going to keep seeing people run into this. |
If anyone can help suggest how to apply this hook in next.js so that it works, I would be very grateful |
Overview
This hook currently throws this error when used with
ReactDOMServer
:This happens because it's trying to access
localStorage
when getting the initial value (runpkg link):react-use-localstorage/src/index.ts
Lines 7 to 9 in af1c0b7
Note: The function that is passed to
useEffect
isn't executed on a server, so accessinglocalStorage
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:
The text was updated successfully, but these errors were encountered: