Following is the doc I am using to learn React Custom Hooks.
Doc Link - https://react.dev/learn/reusing-logic-with-custom-hooks#when-to-use-custom-hooks
In that page, there is a piece of code -
function useData(url) {
const [data, setData] = useState(null);
useEffect(() => {
if (url) {
let ignore = false;
fetch(url)
.then(response => response.json())
.then(json => {
if (!ignore) {
setData(json);
}
});
return () => {
ignore = true;
};
}
}, [url]);
return data;
}
I am not able to understand the use of ignore
variable in this case. Why do we need to set ignore = true;
in the cleanup phase.
This prevents the effect from trying to modify state if the component is unmounted between the time that the AJAX operation begins and the time that it completes.
If the user is just sitting on the page and essentially waiting for the result then nothing significant would happen here. ignore
would still equal false
, the AJAX operation would complete, and would update state.
However, if the user interacts with the React app during that brief moment such that this component is no longer visible or needed, then the effect's cleanup function will execute as the component is unloaded:
() => {
ignore = true;
}
This will update ignore
so that, even a millisecond later, when the AJAX operation completes the code should essentially "ignore" its result because the component is no longer loaded and that data is no longer needed. (And trying to update state in a component that's no longer loaded is likely to result in a warning or error anyway.)