useBoolean – A Hook to toggle a Boolean Value in React.js

Toggling a boolean value is a common task in many React applications, but it can be cumbersome to manage state and logic across components.

React Hooks provide a clean and reusable way to handle stateful logic, and a toggle hook is a simple yet powerful example of how Hooks can simplify your code.

In this blog post, we’ll explore how to create a toggle hook in React that toggles a boolean value and returns the current value and a toggle function.

useBoolean Hook Code

Here’s a hook to toggle a boolean value in React.js with TypeScript:

import { useState } from "react";

const useToggle = (initialValue: boolean): [boolean, () => void] => {
  const [value, setValue] = useState<boolean>(initialValue);

  const toggleValue = () => {
    setValue((prevValue) => !prevValue);
  };

  return [value, toggleValue];
};

export default useToggle;

useBoolean Hook Code Usage Example

You can use this hook by importing it into your React component and then calling it like this:

import useToggle from "./useToggle";

function MyComponent() {
  const [isToggled, toggleIsToggled] = useToggle(false);

  return (
    <div>
      <button onClick={toggleIsToggled}>Toggle</button>
      {isToggled ? <p>It's toggled!</p> : <p>It's not toggled yet.</p>}
    </div>
  );
}

Explanation

In this example, the useToggle hook takes an initial value for the boolean and returns a tuple with the current value and a function to toggle it.

The toggleValue function uses the setValue function returned by useState to set the new value of the boolean. In the component, we destructure the tuple into isToggled and toggleIsToggled and use them to update the UI when the button is clicked.

,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.