Theo's Typesafe CultTTC
Theo's Typesafe Cult14mo ago
5 replies
Bart

How to add event listeners in React without useEffect

I heard theo say in multiple videos that useEffect should be used only when nececairy. I was wondering if there is a better way to add this event listener without using useEffect.

useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape") setIsEditProfileModalOpen(false)
}
window.addEventListener("keydown", handleEscape)
return () => window.removeEventListener("keydown", handleEscape)
}, [])
Was this page helpful?