ably / ably-js

Javascript, Node, Typescript, React, React Native client library SDK for Ably realtime messaging service
https://ably.com/download
Apache License 2.0
311 stars 55 forks source link

Right way to clean up listeners #1803

Open yishay-at-bay opened 2 months ago

yishay-at-bay commented 2 months ago

Hi

If I use React

useEffect(() => {
    const connectionChangeCallback = (
      connectionState: ConnectionStateChange,
    ) => {
      ...
    };

    client?.connection?.on(connectionChangeCallback);

    return () => client?.connection?.off(connectionChangeCallback);
  }, [client]);

Does that the right way to clean up that listener when the component unmounts?

┆Issue is synchronized with this Jira Task by Unito

VeskeR commented 2 months ago

Hi @yishay-at-bay !

Yes, this is the correct way to clean up connection events listeners when component unmounts.

You can also take a look at useEventListener hook from our ably/react module for some inspiration if you would like to extract that bit of code into a reusable hook for your application.