Kyle Shevlin

Software Engineer

Snippet

useBool()

edit
0 strokes bestowed

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: () => {
        setState(true)
      },
      off: () => {
        setState(false)
      },
      toggle: () => {
        setState(s => !s)
      },
      reset: () => {
        setState(initialState)
      },
    }),
    [initialState]
  )

  return [state, handlers]
}

Finished reading?

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


Are you, or the company you work for, struggling with something mentioned in this article?
Would you benefit from a live training session?
Let's Talk
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.

Let's talk some more about JavaScript, TypeScript, React, and software engineering.

I write a newsletter to share my thoughts and the projects I'm working on. I would love for you to join the conversation. You can unsubscribe at any time.

Array.reduce() Logo
Array.reduce()

Check out my courses!

Liked the post? You might like my courses, too. Click the button to view this course or go to Courses for more information.
View the course
I would like give thanks to those who have contributed fixes and updates to this blog. If you see something that needs some love, you can join them. This blog is open sourced at https://github.com/kyleshevlin/blog
alexloudenjacobwsmithbryndymentJacobMGEvanseclectic-codingjhsukgcreativeerikvorhesHaroenvmarktnoonandependabotmarcuslyonsbrentmclarkfederico-fiorinimedayzTowardsDeathFanchGadjonoahmateenbrandonpittmanmattridley
©2023 Kyle Shevlin. All Rights Reserved.