Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  126] [ 5]  / answers: 1 / hits: 188603  / 5 Years ago, mon, april 8, 2019, 12:00:00

I am following a Udemy course on how to register events with hooks, the instructor gave the below code:



  const [userText, setUserText] = useState('');

const handleUserKeyPress = event => {
const { key, keyCode } = event;

if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
};

useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);

return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
});

return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);


Now it works great but I'm not convinced that this is the right way. The reason is, if I understand correctly, on each and every re-render, events will keep registering and deregistering every time and I simply don't think it is the right way to go about it.



So I made a slight modification to the useEffect hooks to below



useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);

return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);


By having an empty array as the second argument, letting the component to only run the effect once, imitating componentDidMount. And when I try out the result, it's weird that on every key I type, instead of appending, it's overwritten instead.



I was expecting setUserText(${userText}${key}); to have new typed key append to current state and set as a new state but instead, it's forgetting the old state and rewriting with the new state.



Was it really the correct way that we should register and deregister event on every re-render?


More From » reactjs

 Answers
77

The best way to go about such scenarios is to see what you are doing in the event handler.


If you are simply setting state using previous state, it's best to use the callback pattern and register the event listeners only on initial mount.


If you do not use the callback pattern, the listeners reference along with its lexical scope is being used by the event listener but a new function is created with updated closure on each render; hence in the handler you will not be able to access the updated state


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>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);

[#52289] Monday, April 1, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
meadowe

Total Points: 0
Total Questions: 97
Total Answers: 97

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
meadowe questions
Thu, Aug 5, 21, 00:00, 3 Years ago
Thu, Jul 9, 20, 00:00, 4 Years ago
Mon, Jun 8, 20, 00:00, 4 Years ago
Sun, Feb 9, 20, 00:00, 4 Years ago
;