In React Hooks documents it is shown how to removeEventListener during the component\'s cleanup phase. https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-
You can put the handleKeyUp
function inside of the function given to useEffect
and only add the listener and return a cleanup function when collapsed
is false.
useEffect(() => {
if (!collapsed) {
function handleKeyUp(event) {
switch (event.key) {
case "Escape":
setCollapsed(true);
break;
}
}
window.addEventListener("keyup", handleKeyUp);
return () => window.removeEventListener("keyup", handleKeyUp);
}
}, [collapsed]);