Fix: Infinite re-render and button clicking bug introduced in last PR #4646
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix: Resolve infinite loop in useFloatingToolbar hook (v2)
Problem
The floating toolbar was causing infinite re-renders under certain conditions, leading to performance issues and potential browser hangs. This occurred when users interacted with text selections while the toolbar was visible.
Additionally, an initial attempt to fix this issue by simply removing the open dependency broke critical button-click functionality, making toolbar buttons unclickable.
Root Cause Analysis
The third useEffect in useFloatingToolbar had open in its dependency array while also calling setOpen inside the effect, creating a feedback loop:
Why the first fix failed: Simply removing open from the dependency array broke the (mousedown && !open) condition, which prevents a race condition during button clicks. When a user clicks a toolbar button:
The (mousedown && !open) condition was specifically designed to prevent closing the toolbar during mousedown when it's already open, allowing click events to complete.
Solution
Use the functional setState pattern to access current state without creating a dependency cycle:
Why This Works
✅ Eliminates infinite loop: No open in dependency array
✅ Preserves button functionality: Uses prevOpen to maintain event timing logic
✅ Same behavior: Toolbar opens/closes exactly as before
✅ Performance: No more endless re-renders
Files Changed
packages/floating/src/hooks/useFloatingToolbar.ts
This solution demonstrates the power of React's functional setState pattern for resolving dependency cycles while preserving critical component behavior.