How to Create useToggle Hook in React: Simple Custom Hook Guide
Create a
useToggle hook in React by using useState to hold a boolean value and returning that value with a function to toggle it. This custom hook simplifies toggling true/false states in components with a clean API.Syntax
The useToggle hook uses React's useState to store a boolean state. It returns an array with the current boolean value and a function to toggle it. You can also pass an optional initial value.
- initialValue: Optional boolean to set the starting state (default is false).
- toggle: Function to switch the state between true and false.
- value: Current boolean state.
javascript
import { useState } from 'react'; function useToggle(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = () => setValue(v => !v); return [value, toggle]; }
Example
This example shows a button that toggles between "ON" and "OFF" states using the useToggle hook. Clicking the button switches the state and updates the displayed text.
javascript
import React from 'react'; function useToggle(initialValue = false) { const [value, setValue] = React.useState(initialValue); const toggle = () => setValue(v => !v); return [value, toggle]; } export default function ToggleButton() { const [isOn, toggleIsOn] = useToggle(false); return ( <button onClick={toggleIsOn} aria-pressed={isOn}> {isOn ? 'ON' : 'OFF'} </button> ); }
Output
A button labeled 'OFF' initially. Clicking it changes the label to 'ON', clicking again toggles back to 'OFF'.
Common Pitfalls
Common mistakes include:
- Not using the functional form of
setStateinside the toggle function, which can cause stale state issues. - Forgetting to provide a default initial value, which may lead to
undefinedstate. - Returning an object or different structure instead of an array, which breaks the expected usage pattern.
javascript
import { useState } from 'react'; // Wrong: Not using functional update, may cause bugs function useToggleWrong(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = () => setValue(!value); // stale closure if used in async return [value, toggle]; } // Right: Use functional update to always get latest state function useToggleRight(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = () => setValue(v => !v); return [value, toggle]; }
Quick Reference
Remember these tips when using useToggle:
- Use functional updates in
setStateto avoid stale state. - Provide a default initial value to keep state predictable.
- Return an array with [value, toggle] for easy destructuring.
- Use
aria-pressedon toggle buttons for accessibility.
Key Takeaways
Create useToggle with useState to manage boolean state simply.
Always use functional updates in toggle to avoid stale state bugs.
Return [value, toggle] array for easy use in components.
Provide a default initial value to keep state consistent.
Use aria attributes for accessible toggle buttons.