skip to Main Content

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?

2

Answers


  1. 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();
        };
      }, []);
    
    Login or Signup to reply.
  2. 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();
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search