reactjs / reactjs/react.dev

useEffect Clean-Up Function Executes After Component is Removed

Open
#3,427 6 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

This behavior has changes in React version 17.0.x.

Clean-up function should execute when the component unmounts, and I've noticed in React v.17 by the time cleanup function executes, React referenced elements are no longer available.

Working example with React v.16
Example with React v.17

Notice unmountSuccessful logs before divRef in React v.17 example.

This is the only relevant change I noticed from the changelog.

If the behavior of useEffect clean-up has changed it should be reflected on the docs.

Code Snippet:

const App = () => {
  const divRef = React.useRef(null);
  
  React.useEffect(() => {
    console.log('divRef ::', divRef.current)
    return function cleanUp() {
      console.log('[cleanUp] divRef ::', divRef.current)
    }
  }, [])
  return (
    <div ref={divRef}>
      Open Browser's Console For Output
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

const unmountApp = () => {
  console.log('unmounting root...')
  const node = document.getElementById('root');
  const unmountSuccessful = ReactDOM.unmountComponentAtNode(node);
  console.log('unmountSuccessful ::', unmountSuccessful)
};

window.setTimeout(unmountApp, 1500);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the React useEffect documentation linked in the issue and compare its cleanup wording with the React 17 behavior shown in the two CodePen examples. Read the linked changelog pull request for the relevant change. Done means the documentation accurately explains when cleanup runs and whether referenced elements remain available.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.