My requirements are as below,
- Dashboard page (https://localhost:3000) shows 1000 records
- User applied filter on dashboard page (only 2 records are shown after filter)
- User clicked on row and entered into details component(https://localhost:3000/details/1)
- User clicked on "back" button on details component
- Dashboard page loads(https://localhost:3000) and shows 1000 records, I expect to show only two rows here and stop re-render the component
This is how my routes are
<div>
<HeaderComponent></HeaderComponent>
<Route exact path={"/"} component={Dashboard} />
<Route exact path={Routes.Details} component={DetailsComponent} />
<ScrollToTop />
</div>
First, your Dashboard component should get some param states which would be passed to your fetch function & would be dependency passed to your useEffect hook. in the Dashboard you should have some code like this:
Now, when you are pushed to this route, you would have the items based on the params that are being passed from that
history.push()orhistory.back()action like this. (don't forget to implement that)Now you have a few options for caching. you can either cache the param value or the items themselves or an array of their ids, based on your state-management strategy (You can even pass it back and forth between dashboard & detail component if you want). for example, you can have a useItems() hook which gets the params as the arguments & then returns the relevant items.
there you can have cache data however you like, so you can serve that if there's no need for refetching. My own prefered solution for that would be using react-query, in which you would have code like this:
So if you set up react-query correctly, you would always have cached data of all the requests you have sent to the server & would use that unless they have become stale, which in that case, it would be refetched. you can read more about it here