Skip to content

Correct usage with React? (OR) SafeEmitter fires old events #8

@subvertallchris

Description

@subvertallchris

Hello! I feel like maybe I'm doing something wrong because I'm seeing some unexpected behavior.

I have a React component that needs to be informed of emitted actions. I setup a simple SafeEmitter that emits an action when an external event occurs. This emitter is subscribed to from within a React useEffect hook that calls a callback function. It goes a little something like this:

  • Component mounts, calls hook function which sets emitter.on(cb)
  • Events occur, 1 event results in 1 emitted action and 1 cb()
  • Component unmounts, callback is expected to be GCed here
  • Component mounts again, calls hook function again which sets emitter.on(cb) with a new version of cb
  • EXPECTED BEHAVIOR: 1 event results in 1 emitted actions and 1 call to the updated cb()
  • ACTUAL BEHAVIOR: 1 event results in 2 emitted actions and 2 calls to each of the versions of cb() -- it never GCs the first one

If the component mounts and unmounts ten times, it will call each of the ten versions of the callback function -- they will never be garbage collected.

Am I using it wrong? I don't see an explicit unlisten action for SafeEmitter, it seems pretty straightforward.

Apologies for how React-specific this is. I thought about trying to make a Sandbox to demonstrate it but thought I'd ping you about it first to see if anything quick jumps to mind.

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions