Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/x/components/sender/hooks/use-speech.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,22 @@ export default function useSpeech(
}
});

// Cleanup SpeechRecognition on component unmount
React.useEffect(() => {
return () => {
if (recognitionRef.current) {
try {
recognitionRef.current.stop();
} catch (e) {
// Recognition might not be started
}
recognitionRef.current.onstart = null;
recognitionRef.current.onend = null;
recognitionRef.current.onresult = null;
recognitionRef.current = null;
}
Comment on lines +140 to +150
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current cleanup logic calls recognitionRef.current.stop() before nullifying the event handlers. The stop() method can trigger the onend event handler, which in turn calls setRecording(false). Since this cleanup function runs on component unmount, this will cause a state update on an unmounted component, leading to a warning from React.

To prevent this, the event handlers should be nullified before calling stop(). It's also slightly cleaner to store recognitionRef.current in a local variable to avoid repeated property access.

      const recognition = recognitionRef.current;
      if (recognition) {
        // Nullify handlers first to prevent state updates on an unmounted component.
        recognition.onstart = null;
        recognition.onend = null;
        recognition.onresult = null;

        try {
          recognition.stop();
        } catch (e) {
          // Recognition might not be started
        }
        recognitionRef.current = null;
      }

};
}, []);

return [mergedAllowSpeech, triggerSpeech, recording] as const;
}
Loading