Skip to content

useToggle

React hook to toggle a boolean value.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useToggle
sh
npx @novajslabs/cli add useToggle
sh
pnpm dlx @novajslabs/cli add useToggle

Or copy and paste the code into your project:

ts
import { useState } from "react";

export const useToggle = (initialValue: boolean) => {
  const [current, setCurrent] = useState(initialValue);

  const handleToggle = () => setCurrent((prev) => !prev);

  return { current, handleToggle };
};
js
import { useState } from "react";

export const useToggle = (initialValue) => {
  const [current, setCurrent] = useState(initialValue);

  const handleToggle = () => setCurrent((prev) => !prev);

  return { current, handleToggle };
};

Requirements

React 16.8 or higher

Parameters

initialValue required

Type: boolean

The initial value of the boolean.

Return values

current

Type: boolean

The current value of the boolean.

handleToggle

Type: function

Toggle the boolean value.

Example

tsx
import { useToggle } from "./hooks/useToggle";

const App = () => {
  const { current, handleToggle } = useToggle(false);

  return (
    <div>
      <p>Current value: {current ? "True" : "False"}</p>
      <button onClick={handleToggle}>Toggle value</button>
    </div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Implementing a toggle switch for enabling/disabling a dark mode feature in a web application
  • Creating a collapsible section or accordion component with expand/collapse functionality
  • Adding a toggle button to show/hide additional details or information in a user profile view
  • Developing a toggle switch for switching between different view modes (e.g., grid view vs. list view) in a product catalog