This post was formerly called useSwitch.

I can’t tell you how many times I’ve needed some binary (boolean) state management.

Copy/paste this and change it to suit whatever needs you have.

type UseBoolHandlers = {
   * Set state to true
  on: () => void;
   * Set state to false
  off: () = void;
   * Toggle state
  toggle: () => void;
   * Reset to `initialState`
  reset: () => void;

function useBool(initialState = false): [boolean, Handlers] {
  const [state, setState] = React.useState(initialState)

  const handlers = React.useMemo(
    () => ({
      on: () => {
      off: () => {
      toggle: () => {
        setState(s => !s)
      reset: () => {

  return [state, handlers]

Finished reading?
Liked the post? Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.

Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, TypeScript, React and frontend web development.
Good software by good people.
Visit to learn more
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.
Logo for Introduction to State Machines and XState
Introduction to State Machines and XState
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.