JAVASCRIPT
Simplify Boolean State with useToggle Hook
Effortlessly manage boolean states in React components using a custom `useToggle` hook, providing a simple function to switch values.
import { useState, useCallback } from 'react';
const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(currentValue => !currentValue);
}, []);
return [value, toggle];
};
export default useToggle;
How it works: This `useToggle` hook abstracts the logic for managing a boolean state. It takes an optional `initialValue` and returns the current boolean state and a `toggle` function. The `toggle` function uses `useCallback` to ensure it remains stable across re-renders, preventing unnecessary re-renders of child components that receive it as a prop.