I only use useEffect() in one place in my app as follows:
useEffect(() => {
document.body.addEventListener('click', bodyClicked);
return () => {
document.body.removeEventListener('click', bodyClicked);
};
}, [bodyClicked]);
function bodyClicked() {
dispatch({type: 'toggleMenuPageOff'});
}
I am getting this warning:
react_devtools_backend.js:4061 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at WEBPACK_DEFAULT_EXPORT (http://localhost:3000/bundle.js:4146:70) at div
Why is this a memory leak and how can I write it correctly to remove the warning?
You're creating an infinite loop. the function you're if inside the components code is being recreated on each rerender which means it will trigger useEffect and therefore be called again and again...