Royalty
Royalty

Reputation: 513

Can't perform a React state update on an unmounted component with useEffect hook

I have

useEffect(() => {
        setLoading(true);
        axios
            .get(url, {params})
            .then(data => {
                setData(data || []);
                setLoading(false);
            })
            .catch(() => {
                showToast('Load data failed!', 'error');
                setLoading(false);
            });

    }, [params]);

It gives me

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Ok, the question IS NOT HOW TO SOLVE IT. When I use setLoading(false) after axios promise it works fine but inside of promise (e.g. above) it always gives me warning. Actually I want to know WHY IT HAPPENS SO? Is there anybody who may explain me in a nutshell a flow of code above (the process how code above works with warning) and maybe give some best practices on using hooks.

Upvotes: 1

Views: 539

Answers (1)

user13198697
user13198697

Reputation:

you need clean up function. this means you should call function end of useEffect function. when dependencie is changes (params as your example ) calls that function. so we would be able controll when component mounts/unmounts

useEffect(() => {
  let cancelled = false;
  setLoading(false);
  async function fetchData() {
    try {
      const response = await axios.get(url, { params });
      if (!cancelled) {
        setData(response.data);
        setLoading(false);
      }
    } catch (e) {
      if (!cancelled) {
        showToast(e.message, "error");
        setLoading(false);
      }
    }
  }
  fetchData();
  // clean up here
  return () => {
    cancelled = true;
  };
}, [params]);

WHY IT HAPPENS SO?

Imagine your request is goes slow, and the component has already unmounted when the async request finishes. this time throws this warning

Upvotes: 2

Related Questions