Skip to content

Instantly share code, notes, and snippets.

@tvler tvler/useNewKey.jsx
Last active Apr 2, 2020

Embed
What would you like to do?
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
You can’t perform that action at this time.