Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use of conditional boolean in React hook

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading