A React hook for controlling a boolean value with toggle, on, and off callbacks
npm install @react-hook/switchnpm i @react-hook/switch
A React hook for controlling a boolean value with toggle, on, and off callbacks. This
is extremely useful for adding controlled/uncontrolled component behavior to components
like , , , etc.
``jsx harmony
import useSwitch from '@react-hook/switch'
// Basic usage
const Component = (props) => {
const [value, toggle] = useSwitch(false /default value/)
return (
<>
Value: {value}
{/ toggles the current value to its opposite/}
{/ toggles the current value to true/}
{/ toggles the current value to false/}
>
)
}
// Creating a toggle component with a controlled and uncontrolled
// value pattern
const Toggle = ({value: controlledValue, defaultValue, onChange}) => {
const [value, toggle] = useSwitch(defaultValue, controlledValue, onChange)
return (
<>
Value: {value}
>
)
}
`
``
function useSwitch(defaultValue?: boolean, controlledValue?: boolean, onChange?: (value: boolean, prevValue: boolean) => any): readonly [boolean, (() => void) & {
on: () => void;
off: () => void;
}]
#### Arguments
| Argument | Type | Default | Required? | Description |
| --------------- | ------------------------- | ----------- | --------- | ------------------------------------------------------------------------------- |
| defaultValue | boolean | false | No | Sets the default value of the switch |boolean
| controlledValue | | undefined | No | Sets the controlled value of the switch, which will override the defaultValue |(value: boolean) => any
| onChange | | undefined | No | A callback invoked whenever toggle callbacks that change state are invoked |
#### Returns [value: boolean, toggle: Toggle]
| Variable | Type | Description |
| -------- | ------------------------------------------------ | -------------------------------------------------------------------------- |
| value | boolean | Defines the initial value |() => void & {on: () => void, off: () => void}
| toggle | | If the value is true, calling this will make it false and vice-versa |
#### () => void & {on: () => void, off: () => void}
| Method | Type | Description |
| ------ | ------------ | ------------------------------- |
| on | () => void | Switches the value to true |() => void
| off | | Switches the value to false` |
MIT