Skip to content

Instantly share code, notes, and snippets.

@codemile
Last active December 30, 2021 20:04
Show Gist options
  • Save codemile/321dcc7918b36c1fcf409eaf7f64843e to your computer and use it in GitHub Desktop.
Save codemile/321dcc7918b36c1fcf409eaf7f64843e to your computer and use it in GitHub Desktop.
Hook that toggles a boolean state.
import {useCallback, useState} from 'react';
const useToggle = (init: boolean = false): [boolean, (v: unknown) => void] => {
const [toggle, setToggle] = useState(init);
const callback = useCallback((value) => {
setToggle((prev) => (typeof value === 'boolean' ? value : !prev));
}, []);
return [toggle, callback];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment