I have a React app(Gatsby) and using @reach/router.
There are multiple pages like user page, follower page...etc.
Fetching data in useEffect hook and here is the problem.
When I navigate to another page from the current page, I'm passing a param, sending it to the next component, for example to a user page, then calling API in useEffect hook in the component with the param. Then you can go to another component like follower page with a param, calling api in useEffect again. When I try to go back with browser back, the previous data updates again. Ideally I don't want it to get updated every time when I go back to the previous page.
I understand that this happens because I'm calling it in the useEffect hook. Thought about passing data as props with navigate (ex. navigate("/follower", state: { data })), but I think navigate to the page first and fetching data is the best solution for users because when fetching data is taking some time, I want to show skeleton or a loading indicator in the next page. The ideal experience is something like twitter.
Not sure this isn't working because I'm using @reach/router instead of react-router-dom
Any advise is appreciated.
EDIT:
Apologise for my poor explanation.
My problem here is when I keep going back to previous pages like this user page → follower → (another)user → follower ... , browser doesn't remember what were there and useEffect fires everytime. It wasn't happening with react-router before?
My guess is that since I'm using GatsbyJS(SSR) and client-side routing, somehow it generates pages every time even the browser back triggered instead painting it again? I'm not familiar with SSR w/ cliet-routing, hoping to get some info somewhere..
The only way it comes to my mind is using local storage or cookies, within a
useEffectwithdeps([]), otherwise, each rendering of the page (moving back and forward for example) will trigger again all side-effects available.Alternatively, you can use
useEffect'sdeps, to only fire theuseEffectif the needed dependency has changed.You
deps(yourDeps) can also check values that you are sending through the location state or from local storate/cookies.You can also use
useRefhook to store "old" values from references but given your generic explanation, I'm not sure which case fits you better.