CharlesStover/reactn

Dispatching in useEffect throws a warning.

quisido opened this issue · 4 comments

A couple users in the Discord reported this 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".

Example code:

const [,dispatch] = useDispatch('abc');
useEffect(() => {
  const unsubscribe = emitter.on('event', () => {
    dispatch();
  });
  return () => {
    unsubscribe();
  };
}, [dispatch]);

A user reports that performance analysis confirmed no memory leak, meaning this is likely a single no-op during the unsubscription process and has no impact on production environments, just an annoying warning for developers.

Needs a minimal reproduction for better root cause analysis.

My guess: dispatch hasn't changed, so cleanup and thus unsubscribe isn't called when the component is unmounted. Try just using [].

Thanks for the insight @lookfirst .

I believe the unsubscribe function should fire unconditionally on unmount, even if the dependencies have not changed.

Closing this until a minimal reproduction exists.

My guess: dispatch hasn't changed, so cleanup and thus unsubscribe isn't called when the component is unmounted. Try just using [].

I have the same guess with you. My problem is more weired. My code works in local dev env, but not in production env. However, I'm not able to reproduce my problem. Sorry.