Member-only story
React Tips — Spies, Global Events, and Nav Links
4 min readSep 15, 2020
React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
Register Event with useEffect Hooks
We can register events within the useEffect
callback.
For instance, we can write:
const App = () => {
const [userText, setUserText] = useState(''); const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32) {
setUserText(prevUserText => `${prevUserText}${key}`);
}
}, []); useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress); return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]); return (
<div>
<p>{userText}</p>
</div>
);
}
We listen to the keypress event on the window.
If we press the space key, then the key code will be registered.
Then we can use that to append the state string with the key text.
We just keep appending the key code to the state string.