Reputation: 624
I have a component which registers a key event during initialization. This event triggers API call to fetch random Data.
useEffect(() => {
const keyUpEvent = (event) => {
if (event.code === "Enter") {
event.preventDefault();
fetchRandomData();
}
};
document.addEventListener("keyup", keyUpEvent);
fetchRandomData();
return () => {
setChord({});
document.removeEventListener("Keyup", keyUpEvent);
};
}, []);
But even with the above code, the event is not removed when I navigate between pages and trigger the event by key strokes ( Enter KEY ).
Based on the below image, this happens when I press the key once after multiple page navigations. ( MEMORY LEAK )
PROBLEM :
Why is react not removing the registered event? What is the proper way to remove event listeners..?
Upvotes: 0
Views: 131
Reputation: 12807
You are capitalizing incorrectly. You just change Keyup
in removeEventListener
to keyup
.
Upvotes: 1