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.