ably / ably-chat-js

Ably Chat SDK for JavaScript to build chat experiences at scale
https://ably-livestream-chat-demo.vercel.app/
Apache License 2.0
8 stars 0 forks source link

react: use stable references to event listeners in hooks #338

Closed AndyTWF closed 1 month ago

AndyTWF commented 1 month ago

Context

N/A

Description

A number of our hooks allow users to pass in their own listeners to be able to monitor events such as new messages or occupancy updates, even if the hook exposes the latest data.

At present, we use the listener param in a useEffect to apply listener subscriptions. This causes listener cycling if the hook is called using an inline listener, as the reference changes every time. This behaviour is not desired, as it may cause the subscriber to miss events.

This change fixes the issue by introducing a new internal hook, useEventListenerRef. This hook creates a stable reference to the passed in listener between re-renders. So whilst the underlying listener may change, we avoid cycling subscriptions on every render and thus potentially missing messages.

We also replace all instances of listener use in the other hooks with calls to this new hook, so that the listener passed in is maintained.

Checklist

Testing Instructions (Optional)

On main, try the in-repo demo app using trace level logging. If you type something into the input, you'll see that the useRoomReactions listener unmounts and remounts.

On this branch, you'll see that no longer happens.

github-actions[bot] commented 1 month ago

Coverage Report

Status Category Percentage Covered / Total
🟢 Lines 94.35% (🎯 92%) 2839 / 3009
🟢 Statements 94.35% (🎯 92%) 2839 / 3009
🟢 Functions 96.36% (🎯 93%) 212 / 220
🟢 Branches 94.64% (🎯 93%) 760 / 803
File Coverage
File Stmts % Branch % Funcs % Lines Uncovered Lines
Changed Files
src/react/helper/use-event-listener-ref.ts 100% 100% 100% 100%
src/react/hooks/use-chat-connection.ts 100% 100% 100% 100%
src/react/hooks/use-messages.ts 100% 100% 100% 100%
src/react/hooks/use-occupancy.ts 100% 100% 100% 100%
src/react/hooks/use-presence-listener.ts 89.24% 88.23% 100% 89.24% 115-118, 132-135, 158-163, 167-169
src/react/hooks/use-presence.ts 97.8% 100% 100% 97.8% 126-127
src/react/hooks/use-room-reactions.ts 100% 100% 100% 100%
src/react/hooks/use-room.ts 92.3% 94.11% 100% 92.3% 102-103, 119-121
src/react/hooks/use-typing.ts 96.7% 100% 100% 96.7% 121-123
src/react/types/status-params.ts 0% 0% 0% 0% 1
Generated in workflow #1483