

If not provided, useEffect will call your function on every render. This is the part of the useEffect hook that tells React which bits of state our side-effects are linked to. We need to provide, as a second argument to useEffect, our dependency array.

There's one last thing missing from our useEffect and our hook. This makes it a great place to perform any "cleanup" necessary. The callback inside of useEffect is meant to perform side-effects, but if we return a function from our callback, that function will be executed when the component unmounts. Luckily, useEffect comes with a handy feature just for such a thing: the cleanup function. Using this hook now would cause another event listener to be registered on every render.
Use event key outside keyup function javascript code#
Thus, we named our function “onKeyup.”Īt this point we have functionality, but our code is still broken. alphanumeric keys), and ignores keys like "Escape" and "Enter." It’s convention to name your event listeners “on” + the event name. It only fires for keys that produce a character value (i.e. In case you're curious, listening for keypress is not recommended. Inside useKeypress.js, we're going to create an empty function and export it, define arguments, and write our jsdocs. This is useful for things like modals or menus that you want to be able to close using the "escape" key. This hook registers a listener when a component mounts and performs an action when the chosen key is pressed. The goal of our hook isn't to replace the existing synthetic event onKeypress - that's easy enough to register on an element in your JSX. Nothing fancy, but it's a nice abstraction that makes it a lot easier to add some nice power-user features to your app. In this article we're going to throw together a quick hook that registers an event listener on a keypress and performs an action. Using React's built-in hooks such as useState and useEffect, we can encapsulate and modularize bits of functionality - almost the same way we create reusable components. One of the great patterns to come out of React 16.8 is composable hooks.
