Skip to content

[tooltip] Fix onOpen/onClose callback not firing due to stale state in React 18 batching#48683

Open
cjz9032 wants to merge 1 commit into
mui:masterfrom
cjz9032:fix/tooltip-onopen-onclose-batched-updates
Open

[tooltip] Fix onOpen/onClose callback not firing due to stale state in React 18 batching#48683
cjz9032 wants to merge 1 commit into
mui:masterfrom
cjz9032:fix/tooltip-onopen-onclose-batched-updates

Conversation

@cjz9032

@cjz9032 cjz9032 commented Jun 17, 2026

Copy link
Copy Markdown

Problem

In React 18's automatic batching, setOpenState does not trigger an immediate re-render. When handleClose checks the open variable right after setOpenState, it may read a stale value, causing onClose to be silently skipped. The same issue affects handleOpen.

This is most noticeable in controlled mode where the open prop is managed externally: after mouseLeave triggers internal close logic, onClose never fires, leaving the parent's state out of sync.

Fix

Use a useRef to track the last known open state, synced after each render via useLayoutEffect. Both handleOpen and handleClose capture wasOpen = openRef.current before updating the ref, then use wasOpen for the callback guard condition instead of the potentially stale open variable.

Test

Added a test case that verifies onClose is called when a controlled tooltip (open={false}) is internally opened via mouseOver with enterDelay and then immediately closed via mouseLeave — without waiting for a re-render between the two events.

@code-infra-dashboard

Copy link
Copy Markdown

Deploy preview

https://deploy-preview-48683--material-ui.netlify.app/

Bundle size

Bundle Parsed size Gzip size
@mui/material 🔺+116B(+0.02%) 🔺+57B(+0.04%)
@mui/lab 0B(0.00%) 0B(0.00%)
@mui/private-theming 0B(0.00%) 0B(0.00%)
@mui/system 0B(0.00%) 0B(0.00%)
@mui/utils 0B(0.00%) 0B(0.00%)

Details of bundle changes


Check out the code infra dashboard for more information about this PR.

@mj12albert mj12albert added the scope: tooltip Changes related to the tooltip. label Jun 17, 2026
@mj12albert

Copy link
Copy Markdown
Member

@cjz9032 Thanks for the PR, would you mind providing a Stackblitz or something that can reproduce/demonstrate the bug?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope: tooltip Changes related to the tooltip.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants