re: Memory leak by anonymous functions VIEW POST


I like to write anonymous event handlers on occasion and my work app is all Inversion of Control - so we have a master event bus etc. We just use hooks to add the events and then it's fine as it is properly removed.

We mostly use our master event bus which has a special hook, but the generic one looks like this:

export function useEvent(emitter, pattern, handler) {
    if (!handler) {
        ;[emitter, pattern, handler] = [events, emitter, pattern]
    let runner = (...params) => {
    useEffect(() => {
        if (emitter) {
            if (emitter.addEventListener) {
                emitter.addEventListener(eventName(pattern), runner)
            } else {
                emitter.addListener(eventName(pattern), runner)
        return () => {
            if (emitter.removeEventListener) {
                emitter.removeEventListener(eventName(pattern), runner)
            } else {
                emitter.removeListener(eventName(pattern), runner)

Used like this:

function SomeComponent() {
     useEvent(window, 'resize', ()=>console.log(innerWidth, innerHeight))
code of conduct - report abuse