React 17 runs useEffect cleanup functions asynchronously

Originally appeared on Saeloun Blog.

Effect cleanup functions

React performs the cleanup when the component unmounts.
The useEffect
hook
is built in a way that if we return a function within the method,
it gets executed when the component unmounts.

useEffect(() => {
  // This is the effect itself.
  return () => {
    // This is its cleanup.
  };
});

Until React 17,
the useEffect cleanup mechanism used to run during
commit phase.
This implies that when a component is unmounting,
React would execute the cleanup functions and then update the screen.
It is similar to the behavior of componentWillUnmount in classes.

This is not ideal for larger apps because it slows down large screen transitions (e.g., switching tabs).

In…


Go to Source of this post
Author Of this post:
Title Of post: React 17 runs useEffect cleanup functions asynchronously
Author Link: {authorlink}