Skip to content

Instantly share code, notes, and snippets.

@gragland
Created January 15, 2021 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gragland/642c9b358fc40990012775a493e3acad to your computer and use it in GitHub Desktop.
Save gragland/642c9b358fc40990012775a493e3acad to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
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];
};
@tomasz13nocon
Copy link

I think it's better to use addEventListener("keydown", ...) over onkeydown since the latter can overwrite and be overwritten elsewhere.

@A-Clever-Rabbit
Copy link

A-Clever-Rabbit commented Feb 10, 2021

I think it's better to use addEventListener("keydown", ...) over onkeydown since the latter can overwrite and be overwritten elsewhere.

I agree. I also think the eventListener should be removed in the return of the useEffect to ensure a cleaner hook. I was running into some memory leaks with the default implementation. However this is an awesome hook idea, keep up the good work.

@YuJianghao
Copy link

I think it's better to use addEventListener("keydown", ...) over onkeydown since the latter can overwrite and be overwritten elsewhere.

+1 ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment