Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: React 18 + useEffect cleanup runs immediately after render #24431

Closed
tianhuil opened this issue Apr 24, 2022 · 4 comments
Closed

Bug: React 18 + useEffect cleanup runs immediately after render #24431

tianhuil opened this issue Apr 24, 2022 · 4 comments
Labels
Resolution: Expected Behavior Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@tianhuil
Copy link

React version: 19

Steps To Reproduce

Here is a bare-bones react app with one useEffect: https://github.com/tianhuil/use-effect-demo/

In this one, we log the cleanup side effect to console in v18, which you can verify by running pnpm dev and inspecting the console.

In the next commit we do the same thing in v17, which does not print the same log statement in the console.

Impact

This is pretty important. The cleanup function is used for unsubscribing from listeners and DB subscriptions. This behavior kills those listeners and subscriptions before the first fetch completes!

The current behavior

I expect v18 useEffect cleanup runs immediately (not at unmount)

The expected behavior

I expect v18 to behave as v17.

@tianhuil tianhuil added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 24, 2022
@vkurchatkin
Copy link

In React 18 effects runs effects twice in strict mode (i.e. effect -> cleanup -> effect), so this is totally expected

@eps1lon
Copy link
Collaborator

eps1lon commented Apr 24, 2022

As was mentioned, this is expected behavior that got introduced in React 18: https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

@tianhuil
Copy link
Author

Thanks @vkurchatkin, @eps1lon

@gaearon
Copy link
Collaborator

gaearon commented Jun 16, 2022

We wrote a new page documenting this in detail on the Beta website.

https://beta.reactjs.org/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development

Hope this is helpful. Sorry some links from there are 404 because other pages are still being written.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Resolution: Expected Behavior Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

4 participants