I am building a React application that fetches data from an API when a user opens a page.
The problem is that the user can navigate to another page before the API request finishes. When the request eventually completes, I don't want the old request to update the state of the page that the user has already left.
For example:
useEffect(() => {
fetch("/api/data")
.then(res => res.json())
.then(data => {
setData(data);
});
}, []);
If the component is unmounted before fetch() finishes, what is the recommended way to handle this?
Should I:
Cancel the request using
AbortControllerSimply ignore the response after unmounting
Keep the response in a cache for when the user returns
Use a data-fetching library such as React Query
I would like to understand which approach is appropriate for a normal React application and why.