Light-Keeper / react-singleton-hook

Create singleton hook from regular react hook
MIT License
238 stars 13 forks source link

make SingletonHooksContainer compatible with server components (Next.js) #527

Open szamanr opened 1 month ago

szamanr commented 1 month ago

hi! when using Next.js with app router, all components are considered server components by default, unless you include "use client" directive at the top of the file.

currently, trying to render SingletonHooksContainer in the top-level of the application results in an error:

Error: useState only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component

the workaround is to create a new component with the directive and render that instead of the library component:

"use client";

import { SingletonHooksContainer } from "react-singleton-hook";

export const SingletonHooks = SingletonHooksContainer;

not sure if this issue is specific to next.js or would also occur when using a different setup with react server components. but i think a simple fix would be to include "use client"; at the top of the SingletonHooksContainer file.

thanks!