Skip to content

Instantly share code, notes, and snippets.

@tvler tvler/useNewKey.jsx
Last active Nov 16, 2018

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);
if (Boolean(bool) === Boolean(key % 2)) {
setKey(key + 1);
}
return Math.floor(key / 2);
};
// Ex:
const Component = () => {
const [bool, setBool] = useState(false);
const key = useNewKey(bool);
return (
<>
{key}
<button
onClick={() => {
setBool(!bool);
}}
/>
</>
);
};
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.