Sometimes, we want to register event with React useEffect hooks.
In this article, we’ll look at how to register event with React useEffect hooks.
How to register event with React useEffect hooks
To register event with React useEffect hooks, we can call the window.addEventListener
method in the useEffect
callback.
For instance, we write
//...
const Comp = () => {
const [userText, setUserText] = useState("");
const handleUserKeyPress = useCallback((event) => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText((prevUserText) => `${prevUserText}${key}`);
}
}, []);
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<blockquote>{userText}</blockquote>
</div>
);
};
to create the userText
state with the useState
hook.
Then we creatr the handleUserKeyPress
function that checks for the key that’s pressed.
And we call setUserText
to append the key
pressed to userText
.
Then we call useEffect
with a callback that calls window.addEventListener
to listen to the keydown event.
And handleUserKeyPress
is called when the keydown event is triggered.
The useEffect
callback is run when handleUserKeyPress
changes.
We return a function that calls window.removeEventListener
to remove the keydown listener when handleUserKeyPress
changes.
Conclusion
To register event with React useEffect hooks, we can call the window.addEventListener
method in the useEffect
callback.