Button Toggle (ON/OFF)
Difficulty: Warm-up
Problem Statementβ
Render a button that toggles between ON and OFF on each click.
Live Demoβ
Try the running app below β this is the target behavior for the challenge.
Button Toggle (ON/OFF) β Live Demo
What Interviewers Expectβ
- Single boolean state drives label.
- No duplicated state for label and toggle value.
- Handler uses functional update.
Step-by-Step Implementationβ
Step 1 β Boolean stateβ
Track toggle with one boolean.
const [on, setOn] = useState(false);
Step 2 β Derive label from stateβ
Button text should come from state, not hardcoded toggling.
<button onClick={() => setOn((v) => !v)}>{on ? 'ON' : 'OFF'}</button>
Complete Implementationβ
Copy-paste ready single-file solution. Use this as your reference after attempting the challenge yourself, or paste it into CodeSandbox / StackBlitz to run locally.
App.jsx
import React, {useState} from 'react';
export default function App() {
const [on, setOn] = useState(false);
return (
<button type="button" onClick={() => setOn((v) => !v)}>
{on ? 'ON' : 'OFF'}
</button>
);
}
Final Checklistβ
- UI works for primary flow
- Edge cases handled (empty/disabled/loading where relevant)
- State updates are immutable
- Components are readable and reasonably split
- You can explain trade-offs out loud in an interview
Next Challengeβ
Continue to the next item in the sidebar when you're comfortable implementing this from scratch in 30β45 minutes.