Home > Enterprise >  How to clean up eventListener using event subscription from useEffect?
How to clean up eventListener using event subscription from useEffect?

Time:10-13

I have

React.useEffect(() => {
    const myFn = () => {
      // do something
    };

    AppState.addEventListener('change', myFn);

    return () => {
      AppState.removeEventListener('change', myFn);
    };
  }, []);

which will remove event listener on unmount.

However, with latest react-native, removeEventListener('type', ...) is deprecated, with the message Use the 'remove()' method on the event subscription returned by 'addEventListener()'.

How can you do this? Do you use a ref to store the event subscription?

CodePudding user response:

This is covered in the documentation for removeEventListener():

removeEventListener()

removeEventListener(eventType, listener);

Deprecated. Use the remove() method on the EventSubscription returned by addEventListener().

Using the new pattern with the example code that you showed would look like this:

useEffect(() => {
  const myFn = () => {
    // do something
  };

  const eventSubscription = AppState.addEventListener('change', myFn);

  return () => eventSubscription.remove();
}, []);

CodePudding user response:

As per the documentation, what they are wanting you to do is save the output of addEventListener which will have its own remove method instead of referencing the myFn handler:

React.useEffect(() => {
    const myFn = () => {
      // do something
    };

    const event = AppState.addEventListener('change', myFn);

    return () => {
      event.remove();
    };
  }, []);
  • Related