useBoolean
The useBoolean hook is a custom hook that manages a boolean state in React applications. It provides functions to toggle the state between true
and false
. This hook is useful for handling scenarios where you need to maintain and control a boolean value.
Parameters
function useBoolean(
initialState?: boolean
): [boolean, ToggleFunctions];
initialState
:optional
- The initial state for the boolean value. Defaults tofalse
.
Return Value
The useBoolean hook returns a tuple containing the current boolean state and an object with toggle functions.
type Toggle = "on" | "off" | "toggle";
type ToggleFunctions = Record<Toggle, () => void>;
Usage
Import the useBoolean
hook from hookings
and use it in your React components:
import { useBoolean } from "hookings";
const Component = () => {
const [isOn, toggleFunctions] = useBoolean();
console.log(isOn); // false
const handleToggleOn = () => {
toggleFunctions.on(); // Sets the state to true
};
const handleToggleOff = () => {
toggleFunctions.off(); // Sets the state to false
};
const handleToggle = () => {
toggleFunctions.toggle(); // Toggles the state (from true to false or vice versa)
};
return (
<div>
<button onClick={handleToggleOn}>Toggle On</button>
<button onClick={handleToggleOff}>Toggle Off</button>
<button onClick={handleToggle}>Toggle</button>
</div>
);
};
In this example, the Component
uses the useBoolean
hook to manage a boolean state and provides buttons to interact with the state using the provided toggle functions.
Conclusion
The useBoolean
hook is a helpful tool for managing boolean states in your React applications. By utilizing this hook, you can easily implement functionalities that depend on a true/false value. Enjoy coding! 🚀