usehooks icon indicating copy to clipboard operation
usehooks copied to clipboard

Add documentation on how to use client-hooks and improve errors

Open ottovw opened this issue 2 years ago • 2 comments

After running into a issue using client hooks and server rendering, @tylermcginnis referenced/explained (thanks!) why that error is necessary: https://github.com/uidotdev/usehooks/issues/218#issuecomment-1681205155

It turns out, that happened to multiple users:

  • https://github.com/uidotdev/usehooks/issues/258
  • https://github.com/uidotdev/usehooks/issues/254
  • https://github.com/uidotdev/usehooks/issues/218

Therefore the proposal is to:

  • add a structured docs block to every client hook in the docs (e.g. using the explanation of Tyler) on the website
  • include the url to this explanation within the error message in the code
  • mark client-hooks in the hook overview (maybe also sort?)

useHooks advertises "server-safe" which is a bit misleading. I acknowledge, that it was a user error due to not fully understanding server render. useHooks could make life much easier for the users. My initial experience was pretty frustrating. (Remember Apple's "You're holding it wrong")

Thanks for providing this library.

ottovw avatar Nov 02 '23 21:11 ottovw

Here's a utility component I wrote for client-only hooks:

"use client";

import { useIsClient } from "@uidotdev/usehooks";

const ClientOnly = ({
  children,
  placeholder,
}: {
  children: React.ReactNode;
  placeholder?: React.ReactNode;
}) => {
  const isClient = useIsClient();

  if (!isClient) {
    return placeholder || null;
  }

  return children;
};

export default ClientOnly;

Usage:

<ClientOnly
  placeholder={<div className="fixed inset-0 bg-black z-50" />}
>
  <Preloader video={home.video as VideoType} />
</ClientOnly>

jamesvclements avatar Nov 07 '23 16:11 jamesvclements

I support this suggestion.

What I find strange, if some of these hooks can ONLY really make sense on clients, why require the useIsClient hook or other wrappers?

Could not useLocalStorage hook incorporate isClient tests internally?

wayneschuller avatar Dec 06 '23 22:12 wayneschuller