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

Fix potential dangerous access of ref value in useEffect cleanup #7404

Merged
merged 1 commit into from
Jan 26, 2025

Conversation

Bastian
Copy link
Contributor

@Bastian Bastian commented Jan 23, 2025

Directly accessing the value of a ref in a useEffect cleanup function can lead to problems, as refs “live” outside of React's rendering cycle and it can therefore happen that the value of the ref changes between the first execution and the cleanup.

See ESLint warning:
image

This is not just a theoretical problem. I encountered a bug after upgrading to React 19 while running in dev mode. My callback passed to the onChange prop of a Slider component (which uses useMove internally) was not updated and therefore used a stale variable that was captured by the closure. I believe this is related to React calling the useEffect hooks twice in development mode, although I'm not sure why this only happens with React 19 and not React 18, which introduced this behavior.

Directly accessing the value of a ref in a `useEffect` cleanup function
can lead to problems, as refs "live" outside of React's rendering cycle
and it can therefore happen that the value of the ref changes between
the first execution and the cleanup.
@Bastian
Copy link
Contributor Author

Bastian commented Jan 24, 2025

Follow up: #7406

tl;dr: Refs should probably not be used at all in this case. I would still appreciate it if this PR could be merged as it fixes an immediate bug I have in my code.

@rtivital rtivital merged commit c2920f1 into mantinedev:master Jan 26, 2025
1 check passed
@rtivital
Copy link
Member

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants