Skip to content
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: useLocalStorage is a client-only hook #238

Closed
sadaffathali opened this issue Sep 26, 2023 · 3 comments
Closed

Error: useLocalStorage is a client-only hook #238

sadaffathali opened this issue Sep 26, 2023 · 3 comments

Comments

@sadaffathali
Copy link

sadaffathali commented Sep 26, 2023

I use useLocalStorage in a next-hook, I'll use that hook in the client-side component and still get this error

Error: useLocalStorage is a client-only hook

this is the hook I wrote:

`export default function useUserToken(): UseUserTokenHook {
const [userToken, setUserToken] = useLocalStorage(USER_TOKEN_KEY)

useEffect(() => {
    if (typeof window === 'undefined') {
        return
    }
}, [])

const setToken = (token?: string) => {
    setUserToken(token)
}

if (!userToken) {
    const randomToken = crypto.randomUUID()
    setToken(randomToken)
}

return [userToken as string, setToken]

}`

@sadaffathali sadaffathali changed the title useLocalStorage is a client-only hook Error: useLocalStorage is a client-only hook Sep 26, 2023
@graup
Copy link

graup commented Sep 26, 2023

This is a duplicate of #218

That said, I also ran into this, and I think it is not very intuitive. Maybe it can be improved on this usehooks side.

@tylermcginnis
Copy link
Collaborator

I'll (soon) update the descriptions of all the client-only hooks to clarify the problem/solution.

@gardner
Copy link

gardner commented Dec 1, 2023

If you found this looking for an answer, you can use this component:

ClientOnly.tsx

"use client";
/**
 * Hack to work around next.js hydration
 * @see https://github.com/uidotdev/usehooks/issues/218
 */
import React from 'react';
import { useIsClient } from "@uidotdev/usehooks"

type ClientOnlyProps = {
  children: React.ReactNode;
};

export const ClientOnly: React.FC<ClientOnlyProps> = ({ children }) => {
  const isClient = useIsClient();

  // Render children if on client side, otherwise return null
  return isClient ? <>{children}</> : null;
};

Then wrap your client components:

<ClientOnly>
  <MyComponentThatUsesHooks />
</ClientOnly>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants