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 → false
works consistently.
3. Used in multiple components
- If
useToggle
is 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 🔥