Mohammed M. Ahmed
Mohammed M. Ahmed

Reputation: 71

Using useEffect hook when unmounting with dynamic props

Struggling with hooks here.

I have the following code inside a component:

  const {isLoading, abortRequest} = props;

  const cleanUp = React.useCallback(() => {
    if (isLoading) abortRequest();
  }, [isLoading, abortRequest]);

  React.useEffect(() => {
    return () => {
      cleanUp();
    };
  }, []);

I'm basically attempting to abort an AJAX request when the component unmounts, and the cancellation must only happen when the prop isloading is set to true (initially it's set to false and turns to true when the request is first made). The problem is that I'm getting a stale value for props.isLoading every time and therefore when the component unmounts it never aborts the request. I've tried to include the cleanUp function as a dependency for the useEffect hooks but that makes it run every time the cleanUp callback updates which is not what I want.

Any idea how to solve this?

Upvotes: 1

Views: 227

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85565

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed

You simply do not require to use useCallback hook:

React.useEffect(() => {
    return () => {
      if (isLoading) abortRequest();
    };
  }, [isLoading]);

Upvotes: 1

Related Questions