How to keep data in react after browser back

1.1k Views Asked by At

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 pagefollower(another)userfollower ... , 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..

1

There are 1 best solutions below

0
Ferran Buireu On

The only way it comes to my mind is using local storage or cookies, within a useEffect with deps ([]), otherwise, each rendering of the page (moving back and forward for example) will trigger again all side-effects available.

Alternatively, you can use useEffect's deps, to only fire the useEffect if the needed dependency has changed.

const SomePage=(props)=>{

const isLoggedIn=props.isLoggedIn || localStorage.getItem('logIn')

useEffect(()=>{
// this will only be fired when yourDeps changes

}, [yourDeps])

return {isLoggedIn ? <div>Hello ${user}</div> : <Link to="/log-in">Log in</Link>

}

You deps (yourDeps) can also check values that you are sending through the location state or from local storate/cookies.

You can also use useRef hook to store "old" values from references but given your generic explanation, I'm not sure which case fits you better.