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
peculiarnewbie
useEffect – React
The library for web and native user interfaces
Roland
RolandOP5d ago
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
peculiarnewbie
ah i misunderstood, another option you can try is use useMemo
Sameer
Sameer5d ago
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?
Roland
RolandOP4d ago
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

Did you find this page helpful?