Toggle button with custom hook
React.js
easy
20 mins
Create a React component that displays a toggle button which switches its label between "ON" and "OFF" each time it is clicked. The state should be managed using a custom hook called useToggle.
Requirements
- Use functional components only.
- Implement a custom hook
useToggle(initialValue)that returns:- A boolean state
- A toggle function
- Display "ON" or "OFF" on a button based on the current state.
- On button click, toggle the state.
- The initial state must be "OFF"
Edge Case & Constraints
1. Initial value is false
- Initial value of the hook should be false
Example:
const [value, toggle] = useToggle(false); expect(value).toBe(false);
2. Multiple toggles in a row
- Toggling multiple times in a row should flip the state correctly.
- Ensure
true → false → true → falseworks consistently.
3. Used in multiple components
- If
useToggleis reused in two components, toggling one should not affect the other. - Each instance should manage its own state independently.
4. Re-rendering the parent
- Re-rendering the parent component should not reset the toggle state.
- State should persist unless the component is unmounted.
5. Event handler integrity
- The toggle function should be a stable function (same reference if not changed).
Test Cases
-data-testid="toggle-button" : Selects the button element enabling targeted interaction and assertions in tests.
Preview what you need to build
Companies:
meta
uber
paypal
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
