0

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.

1
  • Yeah, like pointed out in the answer it's to prevent you trying to render (setState), when you no longer mounted. I think the naming ignore is a bit weird, I tend to use mounted = true, and then if (!mounted) {..... etc, it seems more logical. Commented Oct 1, 2023 at 23:27

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.