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
As per the documentation, what they are wanting you to do is save the output of
addEventListener
which will have its ownremove
method instead of referencing themyFn
handler:This is covered in the documentation for
removeEventListener()
:Using the new pattern with the example code that you showed would look like this: