score:1

Accepted answer

you keep registering the listener over and over again. react's documentation regarding usehook mentions how you can clean up certain things, which is exactly what you need for event listeners:

useeffect(() => {
    const listener = function(event) {
        // ...
    };
    document.addeventlistener('keydown', listener);
    return () => {
        // this function gets called when the "effect wears off"
        // which means we need to unregister the listener
        document.removeeventlistener('keydown', listener);
    };
}, [currentid]);

the [currentid] makes react only call the hook whenever currentid changes. react also makes sure that whenever the component gets unmounted, or the hook is about to be re-executed for the same component, that the "cleanup function" gets called. the cleanup function is basically whatever function you return within the hook. if you don't return any, no cleanup function will be called.


Related Query

More Query from same tag