Next.js Discord

Discord Forum

trying to use `use` hook

Unanswered
American Chinchilla posted this in #help-forum
Open in Discord
American ChinchillaOP
so i tried using use hook but its erroring out on client side?

35 Replies

American ChinchillaOP
export async function getUsers() {
  return await API.get<ApiUser[]>("/users");
}
either add "use client" to top of file and make it client, or dont use client hooks in server context
are you sure that the file doesnt have "use client" and also is that in a function and not in root (i cant tell indenting)
@riský either add "use client" to top of file and make it client, or dont use client hooks in server context
American ChinchillaOP
actually i solved those errors by wrapping the component it was in in Suspense but now im facing another error that localStorage is not defined so most likely it runs on server even when i have use client
note that use client still has ssr, so you would have to fetch it in useEffect
American ChinchillaOP
so if i need localStorage i cant really use use(promise)
i myself havent used the use api, but if it does prerendering on server, then probably not
American ChinchillaOP
actually i wanted to use that in layout.tsx so i cant really use next/dynamic so i guess im left with useEffect
the old good useEffect data fetching
you can make a component that is used in the layout tho
the whole layout doesnt need to ne next/dynamic
however i would recommend useEffect more for this because imo fallbacks are way nicer
@riský however i would recommend useEffect more for this because imo fallbacks are way nicer
American ChinchillaOP
currently i already have useLayoutEffect can i sneak that inside it or it needs to be useEffect cause not really sure
lol what is uselayouteffect?
American ChinchillaOP
duh
its not a react or nextjs thing, so... i ask to now what your using
American ChinchillaOP
it is a react thing
wait it may be actually
sorry, i just thought it was a custom hook for layout ;(
makes sense
American ChinchillaOP
yup thats all i know about it
that it is ran before
but not sure if it changes something when i fetch here
but they both meantion its running on browser, so that shouldnt be any issue here
and also, i cant remember where but the nextjs docs once said that they dont recomend using the new use hook for data fetching
and instead would want you to useEffect or use SWR/react-query
American ChinchillaOP
me with already built codebase around use hook fetching
hahahhaa
and may trigger multiple re-renders.
ok i take back what i said if its just as bad as useEffect if its talking about the twice usage in strict mode dev
American ChinchillaOP
i'm relieved
tho you should consider the swr and other data fetching libs
American ChinchillaOP
ill look into swr
as they can dedupe your requests and use the same cache if you have to refetch (lots can get updated without sad prop drilling)