useToggle

Serhii Shramko /

A hook to toggle a boolean value with useToggle.

import { useState, useCallback } from 'react';

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

  const handleToggle = useCallback((newValue) => {
    // If 'newValue' is explicitly provided as a boolean, set 'value' to 'newValue'
    if (typeof newValue === 'boolean') {
      return setValue(newValue);
    }

    // Otherwise, toggle the current state
    return setValue((prev) => !prev);
  }, []);

  return [value, handleToggle];
}

Usage

const App = () => {
  const [isModalOpened, toggleModal] = useToggle();

  return (
    <>
      <p>The modal window is {isModalOpened ? 'opened' : 'closed'}.</p>

      <button onClick={toggleModal}>
        Toggle Modal State
      </button>
    </>
  )
}