useToggle

Handy syntactic sugar around useState, for toggling a boolean value on and off.

JSX
import { useState, useCallback } from 'react';

export default function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = useCallback(() => {
    setValue((v) => !v);
  }, []);

  return [value, toggle];
}
JSX
const App = () => {
  const [isOn, toggleIsOn] = useToggle();
  return (
    <>
      {isOn ? 'The light is on!' : 'Hey who turned off the lights'}
      <button onClick={toggleIsOn}>Press me</button>
    </>
  );
};
Last Updated: