tangle-network / dapp

Monorepo for the Tangle ecosystem.
https://app.tangle.tools
Apache License 2.0
29 stars 15 forks source link

[BUG] Race condition in usePromise hook causes state updates on unmounted components #2574

Closed AtelyPham closed 1 week ago

AtelyPham commented 1 week ago

Is there an existing issue for this?

Current Behavior

The usePromise hook is experiencing a race condition that can lead to state updates being performed on unmounted components. This occurs when the effect runs multiple times before previous promises resolve, potentially causing memory leaks and React warnings about updating state on unmounted components.

Expected Behavior

The hook should only update state for the most recent effect execution and should not attempt to update state on unmounted components.

Steps To Reproduce

  1. Create a component using the usePromise hook with a rapidly changing factory function or dependencies.
  2. Trigger multiple re-renders of the component in quick succession.
  3. Unmount the component before all promises have resolved.
  4. Observe React warnings in the console about updating state on an unmounted component.

Screenshot

No response

Anything else?

The current implementation uses an isMounted ref to check if the component is still mounted before updating state. However, this check is insufficient in scenarios where the effect runs multiple times before the previous promise resolves.

Proposed solution: Implement an additional isSubscribed flag within the effect to properly manage the subscription state for each specific effect execution. This will ensure that only the most recent effect execution can update the component's state, preventing stale updates from previous executions.