Skip to content

fix(react): stale onCapture/onCancel closure in useAskableTextSelectionCapture #307

@vamgan

Description

@vamgan

Summary

useAskableTextSelectionCapture in packages/react/src/useAskableTextSelectionCapture.ts called currentOptions.onCapture?.(packet, selection) and currentOptions.onCancel?.() inside the capture handle callbacks. currentOptions is a snapshot captured at ensureHandle() call time.

In React, parent components re-render and pass new function references on each render. The optionsRef is updated each render to track the latest callbacks, but the handle callbacks used the stale closure instead. The result: if onCapture or onCancel changed between start() and the first capture event, the old callback was invoked.

The useAskableRegionCapture hook already handled this correctly using optionsRef.current.onCapture?.() — the text selection hook was inconsistent.

Impact

React components that inline the callback (common pattern) pass a new function instance on each render. If a selection is captured after a re-render, the previous render's callback fires instead of the current one. This can cause missed state updates or double-firing bugs.

Fix

Replace currentOptions.onCapture?.(...) and currentOptions.onCancel?.() with optionsRef.current.onCapture?.(...) and optionsRef.current.onCancel?.() to always call the latest callback.

Fixed in: claude/create-agents-md-fqfEf

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions