The Konami Code is known as the most famous secret video game code.

Image for post

Konami Code

Today I’ll be creating a set of React Hooks that will enable me to add the famous Konami Code into any React App.

Tracking Key Inputs with a React Hook

I would like to break the key events out (separate from the Konami Code) into it’s own React Hook because I may end up re-using this component in a different app.

For the useInputEvent hook, I want to be able to subscribe to keydown and keyup on mount. I also need to unsubscribe to these events on unmount.

When the keydown and keyup events fire, the code will be stored in thekey state, which is then returned from the React Hook.

import { useEffect, useState } from "react";
export const useInputEvent = () => {
  const [key, setKey] = useState(null);
  useEffect(() => {
    const keyDownHandler = ({ code }) => setKey(code);
    const keyUpHandler = () => setKey(null);
    global.addEventListener('keydown', keyDownHandler);
    global.addEventListener('keyup', keyUpHandler);
    return () => {
      global.removeEventListener("keydown", keyDownHandler);
      global.removeEventListener("keyup", keyUpHandler)
    }
  }, []);
  return key;
}

#web-development #javascript #react-hook #react #game-development

Creating the Konami Code as React Hook
2.40 GEEK