Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@tomasz13nocon tomasz13nocon commented Jan 28, 2021

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

@A-Clever-Rabbit

This comment has been minimized.

Copy link

@A-Clever-Rabbit 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

This comment has been minimized.

Copy link

@YuJianghao YuJianghao commented Mar 4, 2021

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