There's a good chance that at some point, your users will navigate around your app and cause components to unmount before responses to their API requests arrive. When this happens, an error occurs because the component will attempt to update the state values of a component that has been removed.
Thankfully, the useEffect() Hook has a mechanism to clean up things such as pending API requests when the component is removed. Let's take a look at an example of this in action:
import React, { Fragment, useEffect, useState } from "react";
import { Promise } from "bluebird";
Promise.config({ cancellation: true });
function fetchUser() {
return new Promise(resolve => {
setTimeout(() => {
resolve({ id: 1, name: "Adam" });
}, 1000);
});
}
export default function User() {
const [id, setId] = useState("loading...");
const [name, setName] = useState("loading...");
useEffect(() => ...