Skip to content

fix : prevent memory leak in MessageMenu setTimeout cleanup#17120

Open
Amanyadav0315 wants to merge 1 commit intojitsi:masterfrom
Amanyadav0315:analysis/message-menu-issues
Open

fix : prevent memory leak in MessageMenu setTimeout cleanup#17120
Amanyadav0315 wants to merge 1 commit intojitsi:masterfrom
Amanyadav0315:analysis/message-menu-issues

Conversation

@Amanyadav0315
Copy link

Problem

The MessageMenu component currently has a memory leak. When a user clicks "Copy" and the 2-second "Message Copied" notification is active, if the component unmounts before the timeout completes, the state update tries to run on an unmounted component. This can lead to memory leaks and runtime errors.

Solution

To fix this, we made a few improvements:

  • Store the timeout reference: We use useRef to keep track of the setTimeout.
  • Prevent overlapping timeouts: Clearing any existing timeout ensures rapid clicks don’t cause issues.
  • Cleanup on unmount: useEffect clears the timeout when the component unmounts.
  • Fix dependencies: Added the missing handleClose to the useCallback dependency array.

Benefits

  • Eliminates memory leaks when the component unmounts.
  • Handles multiple rapid copy clicks smoothly.
  • Follows React best practices for side-effect cleanup.
  • No changes to the UI or breaking functionality.
  • TypeScript still compiles without errors.

Testing

  • Component unmounts cleanly even during the timeout.
  • Rapid consecutive clicks work as expected.
  • Copy functionality behaves correctly.
  • No TypeScript or runtime errors.

Learnings

This update highlights proper React patterns for managing side effects:

  • Using useRef to store mutable values like timeout IDs.
  • Cleaning up side effects with useEffect.
  • Ensuring correct dependencies in useCallback to avoid stale closures.

- Add timeoutRef to store setTimeout reference
- Clear existing timeout before setting new one
- Add useEffect cleanup to clear timeout on unmount
- Fix missing handleClose dependency in useCallback
- Prevents memory leaks when component unmounts during 2s notification
@jitsi-jenkins
Copy link

Hi, thanks for your contribution!
If you haven't already done so, could you please make sure you sign our CLA (https://jitsi.org/icla for individuals and https://jitsi.org/ccla for corporations)? We would unfortunately be unable to merge your patch unless we have that piece :(.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants