2

Imagine a simple react component

const Upload: React.FC = () => {
    const [done, setDone] = useState(false)
    const upload = async () => {
        await doSomeAsyncStuffHere()
        setDone(true)
    }

    if(done) {
        return <div>success</div>
    }

    return (
        <button onClick={upload}>upload</button>
    )
}

It looks fine at first glance. But what if upload function takes a long time to finish? What if user navigates to another view and the component gets unmounted? When the async task finishes will cause a state update on an unmounted component. This is a no-op and a possible memory leak. What should I do to prevent it?

2
  • 1
    Run it in a useEffect hook with a cleanup function (you shouldn't be causing side effects in a pure function component anyways). This is covered in the hooks FAQ. Commented Dec 21, 2020 at 22:49
  • But I need to run it on user click event, not on render. Commented Dec 21, 2020 at 23:06

1 Answer 1

2

One way of going about it is to create a ref that you set to false when the component is unmounted, and check against this before setting the result of your asynchronous code in the component state.

Example

const Upload: React.FC = () => {
    const isMounted = useRef(true);
    const [done, setDone] = useState(false)
    const upload = async () => {
        await doSomeAsyncStuffHere()
        
        if (isMounted.current) {
            setDone(true)
        }
    }

    useEffect(() => {
        return () => {
            isMounted.current = false;
        };
    }, []);

    if(done) {
        return <div>success</div>
    }

    return (
        <button onClick={upload}>upload</button>
    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fortunately it's no longer necessary to set isMounted refs on components. See this comment from Dan Abramov: github.com/facebook/react/pull/22114

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.