Prevent router.refresh() from remounting client components
I have the following logic:
1) Fetch data in SSR layout, pass to Client Component
2) In Client Component,
useEffect(() => { ... }, []);
with empty dependencies for rendering only once upon component mount. This effect checks if the passed data from the layout is valid, if it isn't, make an API request with client-side infos (need to set cookies, save ip and guest session in database). If the API request succeeds, get valid data from SSR layout with router.refresh()
.
=> Expected behaviour: The useEffect only runs once.
=> Actual behaviour: The useEffect runs twice, because router.refresh() apparently completely remounts the client component. This leads to inconsistent data in my guest sessions.
Any suggestions? :)5 Replies
are you talking in dev or in prod? https://react.dev/reference/react/useEffect#my-effect-runs-twice-when-the-component-mounts
useEffect – React
The library for web and native user interfaces
Both
I am rn taking a different approach, which is just fetching the data via api and not in layout, so i don't have to call router.refresh at all
ah i misunderstood, another option you can try is use useMemo
Do you have some sort limitation for making that component a server component from client? Making it a server component, will remove all this
useEffect
stuff and you would be able to directly fetch inside of that component itself.
can you provide a code sample?Yeah if I call the api from server component cookies won't work
I fixed it by moving the entire logic to the api
Only fetching the url param on server component