-
Notifications
You must be signed in to change notification settings - Fork 0
useToggle
Toggle between two generic values (e.g., "light" and "dark", or 0 and 1). If no secondary value is provided, it elegantly falls back to standard boolean toggling behavior.
A simple boolean toggle, acting much like useBoolean but with a simpler destructured return array.
import { useToggle } from "react-hook-lab";
function BasicToggle() {
const { value: isPlaying, toggle } = useToggle(false);
return (
<div>
<p>Status: {isPlaying ? "Playing" : "Paused"}</p>
<button onClick={toggle}>
{isPlaying ? "Pause" : "Play"}
</button>
</div>
);
}Toggling between two distinct string values (like themes).
import { useToggle } from "react-hook-lab";
function ThemeSwitcher() {
// Toggles between "light" and "dark"
const { value: theme, toggle: toggleTheme } = useToggle("light", "dark");
return (
<div className={`app-${theme}`}>
<p>Current Theme: {theme}</p>
<button onClick={toggleTheme}>Switch Theme</button>
</div>
);
}Toggling between custom objects or complex generic types.
import { useToggle } from "react-hook-lab";
type UserRole = { role: string; accessLevel: number };
const GUEST: UserRole = { role: "Guest", accessLevel: 1 };
const ADMIN: UserRole = { role: "Admin", accessLevel: 10 };
function RoleTester() {
const { value: userRole, toggle: switchRole } = useToggle<UserRole>(GUEST, ADMIN);
return (
<div>
<p>Current Role: {userRole.role} (Level {userRole.accessLevel})</p>
<button onClick={switchRole}>Swap Identity</button>
</div>
);
}-
defaultValue- Type:
T - Description: The primary, initial value.
- Type:
-
reverseValue(Optional)- Type:
T - Description: The secondary value to toggle to. If omitted, the hook assumes boolean behavior and toggles
!value.
- Type:
Returns an object containing:
-
value(T): The current state. -
setValue(Dispatch<SetStateAction<T>>): Standard React state setter function to force a specific value. -
toggle(() => void): A stable, memoized function that switches the state betweendefaultValueandreverseValue.
Under the hood, useToggle manages a generic generic type T via React's useState.
When the toggle function is called:
- If a
reverseValuewas provided, it explicitly checks if the current state strictly equals (===) thedefaultValue. If it does, it sets the state toreverseValue, otherwise it reverts it back todefaultValue. - If
reverseValueisundefined, it simply coerces the previous state to a boolean and negates it via!prev as T.
The toggle method is wrapped in useCallback with dependencies on defaultValue and reverseValue, meaning its reference will remain perfectly stable as long as the provided values don't change identity across renders.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM