Skip to main content

useSwitch

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

Import

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

Other links

import { Stack, Text, useSwitch } from "@vortexlabs/vortex-native";
import { Switch } from "react-native";

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

  return (
    <Stack direction="row" gap={2} align="center">
      <Switch aria-label="Notifications" value={isOn} onValueChange={flipSwitch} />
      <Text>Notifications {isOn ? "on" : "off"}</Text>
    </Stack>
  );
};

Features

  • Manages boolean state with an optional initial value.
  • Provides helpers to turn the state on, off, or toggle it.
  • Works with onPress and onValueChange handlers.

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 a handler. onPress={flipSwitch} receives a press event and toggles; onValueChange={flipSwitch} receives the next boolean and sets it.