Skip to content

Instantly share code, notes, and snippets.

@azmenak
Created October 26, 2020 22:40
Show Gist options
  • Save azmenak/6d75a74b40bd46f0368f6beb85b5e7d9 to your computer and use it in GitHub Desktop.
Save azmenak/6d75a74b40bd46f0368f6beb85b5e7d9 to your computer and use it in GitHub Desktop.
import { useState, useMemo } from "react";
type UseToggleInterface = [
boolean,
{
/**
* Set state value to `true`
*/
on(): void;
/**
* Set state value to `false`
*/
off(): void;
/**
* Invert the current state value
*/
toggle(): void;
}
];
export function useToggle(defaultValue = false): UseToggleInterface {
const [state, setState] = useState(defaultValue);
const toggleControl = useMemo(
() => ({
on: () => {
setState(true);
},
off: () => {
setState(false);
},
toggle: () => {
setState((value) => !value);
},
}),
[]
);
return [state, toggleControl];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment