Last active
April 2, 2020 19:59
-
-
Save tvler/d6011811754f5e9d4952660b6c69ce8d to your computer and use it in GitHub Desktop.
React hook that returns a new key when its passed in value goes from false to true
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// React hook that returns a new key | |
// when its passed in value goes from false to true. | |
// Use this for resetting a child component, firing events, etc! | |
const useNewKey = bool => { | |
const [key, setKey] = useState(bool ? 0 : 1); | |
const newKey = Boolean(bool) === Boolean(key % 2) ? key + 1 : key; | |
useEffect(() => { | |
setKey(newKey); | |
}, [newKey]); | |
return Math.floor(newKey / 2); | |
}; | |
// Ex: | |
const Component = () => { | |
const [bool, setBool] = useState(false); | |
const key = useNewKey(bool); | |
console.log(bool, key); | |
return ( | |
<> | |
<button | |
onClick={() => { | |
setBool(!bool); | |
}} | |
/> | |
{key} | |
{bool.toString()} | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment