Skip to content

useToggle

Toggles a state between an array of values.

Parameters

  • an array of given values to toggle between.

WARNING

Do not include duplicate values in the array, otherwise, it will not work properly.

Return Values

It returns a tuple of 2 values:

IndexNameTypeDescription
0valueAnythe current value.
1toggleFunctionchange to the next value using toggle(), or to a specific value from the given array using toggle(value).

Example Usage

tsx
import { useToggle } from 'react-pre-hooks';

export default function Example() {
  const [background, toggle] = useToggle(['red', 'green', 'blue', 'white']);

  return (
    <main>
      <div style={{ background }} onClick={() => toggle()}></div>
    </main>
  );
}
import { useToggle } from 'react-pre-hooks';

export default function Example() {
  const [background, toggle] = useToggle(['red', 'green', 'blue', 'white']);

  return (
    <main>
      <div style={{ background }} onClick={() => toggle()}></div>
    </main>
  );
}

Released under the MIT License.