JAVASCRIPT
Simplifying Boolean State with useToggle Hook
Implement a concise useToggle React hook to manage simple boolean states (true/false), providing a cleaner and more readable API than direct useState calls.
import React, { useState, useCallback } from 'react';
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(currentValue => !currentValue);
}, []);
return [value, toggle];
}
// Example usage:
function ToggleSwitch() {
const [isOn, toggleIsOn] = useToggle(false);
return (
<div>
<button onClick={toggleIsOn}>
{isOn ? 'ON' : 'OFF'}
</button>
<p>The switch is currently {isOn ? 'active' : 'inactive'}.</p>
</div>
);
}
export default ToggleSwitch;
How it works: The `useToggle` hook provides a simplified way to manage boolean state in React. It takes an optional `initialValue` (defaulting to `false`) and returns a tuple containing the current boolean `value` and a `toggle` function. The `toggle` function flips the current boolean state. It leverages `useState` for state management and `useCallback` to memoize the `toggle` function, preventing unnecessary re-renders of child components that depend on it. This hook makes managing true/false states more concise and readable.