Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active April 2, 2020 19:59
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 tvler/d6011811754f5e9d4952660b6c69ce8d to your computer and use it in GitHub Desktop.
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
// 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