useHooks(🐠)

Easy to understand React Hook recipes by Gabe Ragland
What's all this about?

Hooks are a new addition in React that lets you use state and other React features without writing a class. This website provides easy to understand code examples to help you learn how hooks work and inspire you to take advantage of them in your next project. You may also like my React starter kit ✨️

📩  Get new recipes in your inbox
Join 7,454 subscribers. No spam ever.

useKonamiCode

This hook makes it easy to fire off a function when the visitor enters the Konami Code on their keyboard (↑ ↑ ↓ ↓ ← → ← → B A). Every web app needs a cheat code right? Read through the code comments below to see how it works. Want to try it out? I'm using this hook in production on divjoy.com. Head over there, enter the code within 5 seconds, and something amazing will happen 😻

import React, { useState, useEffect } from 'react';

// Usage
function App(){
  // Call hook with function to fire off  
  // after konami code is entered.
  useKonamiCode(() => {
    alert('Good job 🥳');
  });
  
  // Render whatever you like
  return (
    <div>
      Can you find the easter egg?
    </div>
  );
}

function useKonamiCode(handler) {
  // State to hold array of recently pressed keys
  const [keys, setKeys] = useState([]);

  // Convert stored keys to string and match against konami code string
  const isKonamiCode = keys.join(' ') === 'up up down down left right left right B A';

  useEffect(() => {
    let timeout;

    // When a key is pressed
    window.document.onkeydown = (e) => {
      // Update array of keys in state with new key
      setKeys((currentKeys) => [...currentKeys, getKeyName(e.keyCode)]);
      
      // Clear 5s timeout since key was just pressed
      clearTimeout(timeout);

      // Reset keys if 5s passes so user can try again
      timeout = setTimeout(() => setKeys([]), 5000);
    };
  }, []);

  // Once konami code is entered call handler function
  // and reset keys so user can do it again.
  useEffect(() => {
    if (isKonamiCode) {
      handler();
      setKeys([]);
    }
  }, [isKonamiCode, handler]);

  return isKonamiCode;
}

const getKeyName = (keyCode) => {
  return {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down',
    65: 'A',
    66: 'B',
  }[keyCode];
};
January 14, 2021
•
Next recipe: