Skip to main content

useSwitch

useSwitch is a hook that manages an on or off value, such as whether a menu or panel is open.

Import

import { useSwitch } from '@vortexlabs/vortex';

Allied components

Other links

Switch is off
"use client";

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>
  );
};

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}.

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

Call flipSwitch() to toggle, or pass a boolean to set the state.

const { flipSwitch } = useSwitch();

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

Pass flipSwitch directly to an event handler, such as onClick={flipSwitch}. Receiving an event toggles the state.