DEV Community

loading...

Keyboard input with React Hooks

spaciecat profile image Spacie ・1 min read

Guess who's back, it's me!

I really enjoyed making my first youtube video, so I decided to start a series on creating custom react hooks!

This one's about creating a useKey hook, that allows you to know when a certain keyboard key is pressed. I also cover some of the "rules of hooks", how short circuit evaluation violates the rules, and how to get around that..

Again, any feedback is highly appreciated, thanks for reading and/or watching!


function useKey(key) {
    // Keep track of key state
    const [pressed, setPressed] = useState(false)

    // Does an event match the key we're watching?
    const match = event => key.toLowerCase() == event.key.toLowerCase()

    // Event handlers
    const onDown = event => {
        if (match(event)) setPressed(true)
    }

    const onUp = event => {
        if (match(event)) setPressed(false)
    }

    // Bind and unbind events
    useEffect(() => {
        window.addEventListener("keydown", onDown)
        window.addEventListener("keyup", onUp)
        return () => {
            window.removeEventListener("keydown", onDown)
            window.removeEventListener("keyup", onUp)
        }
    }, [key])

    return pressed
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide