@react-hook/switch
TypeScript icon, indicating that this package has built-in type declarations

1.3.3 • Public • Published

useSwitch()

Bundlephobia Types Build status NPM Version MIT License

npm 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 <Checkbox/>, <Toggle/>, <Modal/>, etc.

Quick Start

import useSwitch from '@react-hook/switch'

// Basic usage
const Component = (props) => {
  const [value, toggle] = useSwitch(false /*default value*/)

  return (
    <>
      <span>Value: {value}</span>
      {/* toggles the current value to its opposite*/}
      <button onClick={toggle}>Toggle</button>
      {/* toggles the current value to true*/}
      <button onClick={toggle.on}>On</button>
      {/* toggles the current value to false*/}
      <button onClick={toggle.off}>On</button>
    </>
  )
}

// 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 (
    <>
      <span>Value: {value}</span>
      <button onClick={toggle}>Toggle</button>
      <button onClick={toggle.on}>On</button>
      <button onClick={toggle.off}>On</button>
    </>
  )
}

API

useSwitch(defaultValue?, controlledValue?, onChange?)

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
controlledValue boolean undefined No Sets the controlled value of the switch, which will override the defaultValue
onChange (value: boolean) => any 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
toggle () => void & {on: () => void, off: () => void} 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
off () => void Switches the value to false

LICENSE

MIT

Package Sidebar

Install

npm i @react-hook/switch

Weekly Downloads

1,125

Version

1.3.3

License

MIT

Unpacked Size

34.2 kB

Total Files

24

Last publish

Collaborators

  • jaredlunde