JAVASCRIPT
React Hook: useToggle for Simple Boolean State Management
Simplify boolean state management in React with `useToggle`. This custom hook provides a state value and helper functions to easily toggle, set true, or set false, perfect for flags.
import { useState, useCallback } from 'react';
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(prev => !prev);
}, []);
const setTrue = useCallback(() => {
setValue(true);
}, []);
const setFalse = useCallback(() => {
setValue(false);
}, []);
return [value, { toggle, setTrue, setFalse }];
}
How it works: The `useToggle` hook abstracts the common pattern of managing a boolean state. It initializes a boolean state using `useState`. It then provides three memoized callback functions: `toggle` to flip the boolean value, `setTrue` to explicitly set it to `true`, and `setFalse` to explicitly set it to `false`. These callbacks are wrapped in `useCallback` for performance optimization, ensuring they don't change on every render unless their dependencies change. The hook returns an array containing the current boolean value and an object of these helper functions.