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)
}, [])
4 Replies
should be fine to use effect for that
mainly to remove the event listener when "removing" it
the only way to add listeners from window is by using useEffect or new api of react, it was something about useSyncExternal, but even react maintainers dont really know the proper way of using it if something is too complicated
this is useEffect's main use case. if you want see what else it can be used for then I recommend checking out the custom hooks for UI.dev: https://github.com/uidotdev/usehooks/blob/main/index.js
GitHub
usehooks/index.js at main · uidotdev/usehooks
A collection of modern, server-safe React hooks – from the ui.dev team - uidotdev/usehooks
Thank you guys! This was really helpful