Skip to content
Source
Sign inSign up
TanStack/hotkeys

fix(react-hotkeys): set hotkey options after ui commit #113 #141

ClosedIanWorley(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/141/headopened

🎯 Changes

This PR prevent UseHotkey from emitting store state changes in mid render. Previously on every rerender the Hotkey Register options were set with SetOptions during the render body. The problem is that store subscribers like useHotkeyRegistrations would receive store update mid render. This would causes yet another rerender while react was rending already. By applying useEffect to setOptions we now wait till the component using UseHotkey has committed its ui changes before triggering a store update.

Issue: #113

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Bug Fixes
    • Fixed hotkey option synchronization so updates happen after UI rendering commits, avoiding React warnings and inconsistent state.
    • Ensured hotkey registration subscribers are notified at the correct time when hotkey options change.
  • Tests
    • Added coverage that verifies the notification order across render, commit, and hotkey store updates when toggling hotkey options.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Review Change Stack

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Path: .coderabbit.yaml

      Review profile: CHILL

      Plan: Pro

      Run ID: 5698ffec-a96c-4dfb-99bb-2ec57df8f5d3

      📥 Commits

      Reviewing files that changed from the base of the PR and between db8c9050182ef17f13cc1a6513199e2556292de2 and 371a1aece17b895133fc8c57ecaf6edf9b3939f1.

      📒 Files selected for processing (3)
      • .changeset/tangy-clubs-divide.md
      • packages/react-hotkeys/src/useHotkey.ts
      • packages/react-hotkeys/tests/useHotkey.test.tsx
      🚧 Files skipped from review as they are similar to previous changes (3)
      • packages/react-hotkeys/tests/useHotkey.test.tsx
      • .changeset/tangy-clubs-divide.md
      • packages/react-hotkeys/src/useHotkey.ts

      📝 Walkthrough

      Walkthrough

      useHotkey now synchronizes registration options in a post-commit effect rather than during render. A regression test verifies subscriber notification timing, and a patch changeset documents the fix.

      Changes

      Hotkey options timing

      Layer / File(s)Summary
      Post-commit options synchronization
      packages/react-hotkeys/src/useHotkey.ts, packages/react-hotkeys/tests/useHotkey.test.tsx, .changeset/tangy-clubs-divide.md
      useHotkey keeps callback updates in render, moves option updates to an effect, tests post-commit notifications, and records a patch changeset.

      Estimated code review effort: 2 (Simple) | ~10 minutes

      Poem

      A rabbit watched the hotkeys hop, And moved their options past render’s stop. The store now waits till commits are through, With tests that mark the timeline true. “No mid-render thumps!” the bunny sings.

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly matches the main change: moving hotkey option updates until after UI commit.
      Description check✅ PassedThe description covers the required sections with a clear change summary, completed checklist, and changeset release impact.
      Docstring Coverage✅ PassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. Actionable comments posted: 2

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@packages/react-hotkeys/src/useHotkey.ts`:
      - Around line 181-193: Move the callback assignment from the render path into
      the existing post-commit useEffect alongside setOptions, so aborted renders
      cannot mutate the active registration. In that effect, update the callback and
      call registrationRef.current.setOptions only when optionsWithoutTarget differ
      from the previously committed options, preserving subscriber stability when
      options are unchanged.
      
      In `@packages/react-hotkeys/tests/useHotkey.test.tsx`:
      - Around line 260-285: Clean up the listener created by
      manager.registrations.subscribe in the “should notify store subscribers after
      commit, not during render” test. Capture the returned unsubscribe function and
      invoke it after the assertion so the timeline closure cannot receive store
      updates from subsequent tests.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: Path: .coderabbit.yaml

      Review profile: CHILL

      Plan: Pro

      Run ID: 4401acc1-20af-4245-a03c-e121826016e2

      📥 Commits

      Reviewing files that changed from the base of the PR and between 6adcc3a1b0a28350eb421f6aeebcf0f94d177817 and db8c9050182ef17f13cc1a6513199e2556292de2.

      📒 Files selected for processing (3)
      • .changeset/tangy-clubs-divide.md
      • packages/react-hotkeys/src/useHotkey.ts
      • packages/react-hotkeys/tests/useHotkey.test.tsx
      @@ -178,9 +178,16 @@
      178178 }
      179179 }, [hotkeyString])
      180180
      181- // Sync callback and options on EVERY render (outside useEffect)
      181+ // Sync callback on EVERY render (outside useEffect)
      182182 // This avoids stale closures - the callback always has access to latest state
      183183 if (registrationRef.current?.isActive) {
      184184 registrationRef.current.callback = callback
      185- registrationRef.current.setOptions(optionsWithoutTarget)
      186185 }
      186+
      187+ // Sync options after the UI commits so store subscribers aren't
      188+ // notified during the render phase
      189+ useEffect(() => {
      190+ if (registrationRef.current?.isActive) {
      191+ registrationRef.current.setOptions(optionsWithoutTarget)
      192+ }
      193+ })
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      # Description: Verify if HotkeyRegistrationHandle.setOptions handles deep/shallow equality internally.
      
      ast-grep run --pattern $'class HotkeyRegistrationHandle {
        $$$
        setOptions($_) {
          $$$
        }
        $$$  
      }' --lang typescript packages/hotkeys/src/hotkey-manager.ts

      Repository: TanStack/hotkeys

      Length of output: 154


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      # Map the relevant files and locate the registration/update logic.
      git ls-files 'packages/react-hotkeys/src/*' 'packages/hotkeys/src/*' | sed 's#^`#FILE` #'
      printf '\n--- setOptions references ---\n'
      rg -n "setOptions|callback = callback|isActive|useEffect|useLayoutEffect" packages/react-hotkeys/src packages/hotkeys/src
      
      printf '\n--- outline: useHotkey.ts ---\n'
      ast-grep outline packages/react-hotkeys/src/useHotkey.ts --view expanded
      
      printf '\n--- outline: hotkey-manager.ts ---\n'
      ast-grep outline packages/hotkeys/src/hotkey-manager.ts --view expanded

      Repository: TanStack/hotkeys

      Length of output: 10133


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '\n--- packages/hotkeys/src/hotkey-manager.ts (setOptions region) ---\n'
      sed -n '360,420p' packages/hotkeys/src/hotkey-manager.ts
      
      printf '\n--- packages/react-hotkeys/src/useHotkey.ts (relevant region) ---\n'
      sed -n '150,210p' packages/react-hotkeys/src/useHotkey.ts
      
      printf '\n--- packages/react-hotkeys/src/useHotkeySequence.ts (similar pattern) ---\n'
      sed -n '160,190p' packages/react-hotkeys/src/useHotkeySequence.ts
      
      printf '\n--- packages/react-hotkeys/src/useHotkeys.ts (similar pattern) ---\n'
      sed -n '170,210p' packages/react-hotkeys/src/useHotkeys.ts

      Repository: TanStack/hotkeys

      Length of output: 5254


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '\n--- Store implementation ---\n'
      rg -n "class Store|setState\\(|state =" packages/hotkeys/src packages/react-hotkeys/src
      
      printf '\n--- likely store file(s) ---\n'
      fd -a "store" packages/hotkeys/src packages/react-hotkeys/src || true
      fd -a "state" packages/hotkeys/src packages/react-hotkeys/src || true
      
      printf '\n--- hotkey-manager around registrations store setup ---\n'
      sed -n '200,260p' packages/hotkeys/src/hotkey-manager.ts

      Repository: TanStack/hotkeys

      Length of output: 4277


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '\n--- Store class definition ---\n'
      sed -n '1,220p' packages/hotkeys/src/key-state-tracker.ts
      
      printf '\n--- hotkey-manager registration handle section ---\n'
      sed -n '330,395p' packages/hotkeys/src/hotkey-manager.ts

      Repository: TanStack/hotkeys

      Length of output: 8174


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      sed -n '1,220p' packages/react-hotkeys/src/useHotkey.ts

      Repository: TanStack/hotkeys

      Length of output: 6244


      Move the callback sync into the commit phase. registrationRef.current.callback = callback mutates the hotkey manager during render, which can leak an aborted concurrent render into the active registration. The useEffect here also runs after every render, and setOptions always publishes a new registration map, so this still churns subscribers even when the options are unchanged. Fold both updates into the post-commit sync and skip setOptions when nothing actually changed.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/react-hotkeys/src/useHotkey.ts` around lines 181 - 193, Move the
      callback assignment from the render path into the existing post-commit useEffect
      alongside setOptions, so aborted renders cannot mutate the active registration.
      In that effect, update the callback and call registrationRef.current.setOptions
      only when optionsWithoutTarget differ from the previously committed options,
      preserving subscriber stability when options are unchanged.

Sign in to join this conversation.