Home > @cascadiacollections/fluentui-compat > useBoolean
useBoolean() function
Hook to store a boolean value and generate callbacks for setting the value to true, false, or toggling it.
This hook is optimized for performance using idiomatic React patterns: - The identity of the callbacks will always stay the same across renders - Uses useMemo
with empty dependencies for stable callback object - Avoids unnecessary function closures and object recreations - Provides stable referential identity for the callbacks object
Signature:
export declare function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks];
Parameters
Parameter |
Type |
Description |
---|---|---|
initialState |
boolean |
Initial boolean value |
[boolean, IUseBooleanCallbacks]
Array with the current value and an object containing the updater callbacks.
Example 1
function MyComponent() {
const [isVisible, { setTrue: show, setFalse: hide, toggle }] = useBoolean(false);
return (
<div>
<p>Visibility: {isVisible ? 'visible' : 'hidden'}</p>
<button onClick={show}>Show</button>
<button onClick={hide}>Hide</button>
<button onClick={toggle}>Toggle</button>
</div>
);
}
Example 2
// Callbacks can be safely used in dependency arrays
function MyComponent() {
const [isEnabled, { setTrue: enable, setFalse: disable }] = useBoolean(false);
const handleApiCall = useCallback(async () => {
disable(); // Disable during API call
try {
await apiCall();
} finally {
enable(); // Re-enable after API call
}
}, [enable, disable]); // Safe to include in deps - identities never change
return <button onClick={handleApiCall} disabled={!isEnabled}>Call API</button>;
}
Example 3
// Multiple boolean states with stable callbacks
function FeatureFlags() {
const [darkMode, darkModeActions] = useBoolean(false);
const [notifications, notificationActions] = useBoolean(true);
const [autoSave, autoSaveActions] = useBoolean(true);
// All callback objects maintain stable identity across renders
return (
<div>
<label>
<input type="checkbox" checked={darkMode} onChange={darkModeActions.toggle} />
Dark Mode
</label>
<label>
<input type="checkbox" checked={notifications} onChange={notificationActions.toggle} />
Notifications
</label>
<label>
<input type="checkbox" checked={autoSave} onChange={autoSaveActions.toggle} />
Auto Save
</label>
</div>
);
}