Skip to main content

useSwitch

Hook for managing boolean state with helpers to turn the value on, turn it off, or toggle it.

Features

  • Manages boolean state with an optional initial value.
  • Provides helpers to turn the state on, off, or toggle it.
  • Works with event handlers such as onClick={flipSwitch}.

Usage

useSwitch returns the current boolean state and helper functions for common state transitions.

import { Button, Stack, Text, useSwitch } from "@vortexlabs/vortex";

const Example = () => {
const { isOn, turnOn, turnOff, flipSwitch } = useSwitch();

return (
  <Stack gap={4}>
    <Text size="body-md-desktop">
      Switch is {isOn ? "on" : "off"}
    </Text>
    <Stack direction="row" gap={3}>
      <Button onClick={turnOn}>Turn on</Button>
      <Button onClick={turnOff}>Turn off</Button>
      <Button onClick={flipSwitch}>Toggle</Button>
    </Stack>
  </Stack>
);
};

Initial Value

Pass true to start the switch in the on state. Without a value, the switch starts as false.

const enabled = useSwitch(true);
const disabled = useSwitch();

enabled.isOn; // true
disabled.isOn; // false

Toggle

flipSwitch toggles the current value when called without a boolean value. It can also set the next state explicitly.

const { flipSwitch } = useSwitch();

flipSwitch(); // toggles current state
flipSwitch(true); // turns on
flipSwitch(false); // turns off

Event Handlers

flipSwitch can be passed directly to event handlers. When React passes the event object automatically, the hook toggles the current value.

Button text changes as the switch toggles.
const { isOn, flipSwitch } = useSwitch();

<Button onClick={flipSwitch}>
{isOn ? "Enabled" : "Disabled"}
</Button>

Common Patterns

Use useSwitch for simple open and closed, active and inactive, or enabled and disabled UI state.

const drawer = useSwitch();
const selected = useSwitch(false);
const editing = useSwitch(true);

drawer.turnOn(); // open drawer
selected.flipSwitch(); // toggle selection
editing.turnOff(); // exit editing mode