React Exercises
Time to practise. Each exercise has a starter playground that already renders something — edit it until it does what the task describes, then compare with the solution. Try on your own first; peeking is allowed after an honest attempt.
| # | Topic | Skills |
|---|---|---|
| 1 | Profile cards | components, props, default values |
| 2 | Like button | useState, events |
| 3 | Traffic light | conditional rendering, lookup objects |
| 4 | Filterable list | lists, keys, filter |
| 5 | Sign-up form | controlled inputs, validation |
| 6 | Countdown timer | useEffect, cleanup, refs |
| 7 | Theme switcher | useContext |
| 8 | Shopping cart | useReducer, derived values |
| 9 | useToggle hook | custom hooks |
Exercise 1: Profile cards
Create a ProfileCard component that shows a name, a role and an emoji avatar. If no emoji is given, show 🙂. Render three cards with different data.
// TODO: give ProfileCard props: name, role, emoji (default '🙂')
function ProfileCard() {
return (
<div style={{ border: '1px solid #ccc', borderRadius: 8, padding: 10, width: 140, textAlign: 'center' }}>
<div style={{ fontSize: 36 }}>❓</div>
<strong>Name</strong>
<div>Role</div>
</div>
);
}
export default function App() {
return (
<div style={{ display: 'flex', gap: 8 }}>
{/* TODO: render three different cards */}
<ProfileCard />
</div>
);
}Show solution
function ProfileCard({ name, role, emoji = '🙂' }) {
return (
<div style={{ border: '1px solid #ccc', borderRadius: 8, padding: 10, width: 140, textAlign: 'center' }}>
<div style={{ fontSize: 36 }}>{emoji}</div>
<strong>{name}</strong>
<div>{role}</div>
</div>
);
}
export default function App() {
return (
<div style={{ display: 'flex', gap: 8 }}>
<ProfileCard name="Lan" role="Designer" emoji="🎨" />
<ProfileCard name="Tuan" role="Developer" emoji="💻" />
<ProfileCard name="Vy" role="Manager" />
</div>
);
}Exercise 2: Like button
Make the button toggle between "🤍 Like" and "❤️ Liked". Show the total likes (start at 41; liking adds one, unliking removes it).
export default function App() {
// TODO: add state for `liked`
const liked = false;
const likes = 41;
return (
<div>
<button style={{ fontSize: 18 }}>{liked ? '❤️ Liked' : '🤍 Like'}</button>
<p>{likes} likes</p>
</div>
);
}Show solution
import { useState } from 'react';
export default function App() {
const [liked, setLiked] = useState(false);
const likes = 41 + (liked ? 1 : 0); // derived, not stored
return (
<div>
<button style={{ fontSize: 18 }} onClick={() => setLiked(!liked)}>
{liked ? '❤️ Liked' : '🤍 Like'}
</button>
<p>{likes} likes</p>
</div>
);
}Exercise 3: Traffic light
Show three circles (red, yellow, green). Only the active one is bright; the others are dimmed (opacity: 0.2). A Next button cycles red → green → yellow → red, and a caption says "Stop", "Go" or "Slow down".
const LIGHTS = ['red', 'yellow', 'green'];
export default function App() {
// TODO: state for the active light and a "Next" button
// TODO: a caption from a lookup object
return (
<div>
<div style={{ background: '#222', padding: 10, borderRadius: 12, width: 60 }}>
{LIGHTS.map((color) => (
<div key={color} style={{ width: 50, height: 50, borderRadius: '50%', background: color, margin: '5px auto' }} />
))}
</div>
</div>
);
}Show solution
import { useState } from 'react';
const LIGHTS = ['red', 'yellow', 'green'];
const NEXT = { red: 'green', green: 'yellow', yellow: 'red' };
const CAPTION = { red: 'Stop', yellow: 'Slow down', green: 'Go' };
export default function App() {
const [active, setActive] = useState('red');
return (
<div>
<div style={{ background: '#222', padding: 10, borderRadius: 12, width: 60 }}>
{LIGHTS.map((color) => (
<div
key={color}
style={{ width: 50, height: 50, borderRadius: '50%', background: color, margin: '5px auto', opacity: color === active ? 1 : 0.2 }}
/>
))}
</div>
<p>{CAPTION[active]}</p>
<button onClick={() => setActive(NEXT[active])}>Next</button>
</div>
);
}Exercise 4: Filterable list
Add a text input that filters the languages (case-insensitive) and a checkbox "Only compiled". Show "No matches" when nothing is left.
const LANGUAGES = [
{ id: 1, name: 'JavaScript', compiled: false },
{ id: 2, name: 'Rust', compiled: true },
{ id: 3, name: 'Python', compiled: false },
{ id: 4, name: 'Go', compiled: true },
{ id: 5, name: 'TypeScript', compiled: true },
{ id: 6, name: 'Ruby', compiled: false },
];
export default function App() {
// TODO: query + onlyCompiled state, filter the list
return (
<div>
<ul>
{LANGUAGES.map((lang) => <li key={lang.id}>{lang.name}</li>)}
</ul>
</div>
);
}Show solution
import { useState } from 'react';
const LANGUAGES = [
{ id: 1, name: 'JavaScript', compiled: false },
{ id: 2, name: 'Rust', compiled: true },
{ id: 3, name: 'Python', compiled: false },
{ id: 4, name: 'Go', compiled: true },
{ id: 5, name: 'TypeScript', compiled: true },
{ id: 6, name: 'Ruby', compiled: false },
];
export default function App() {
const [query, setQuery] = useState('');
const [onlyCompiled, setOnlyCompiled] = useState(false);
const visible = LANGUAGES.filter(
(l) => l.name.toLowerCase().includes(query.toLowerCase()) && (!onlyCompiled || l.compiled)
);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />{' '}
<label>
<input type="checkbox" checked={onlyCompiled} onChange={(e) => setOnlyCompiled(e.target.checked)} /> Only compiled
</label>
<ul>
{visible.map((lang) => <li key={lang.id}>{lang.name}</li>)}
</ul>
{visible.length === 0 && <p>No matches</p>}
</div>
);
}Exercise 5: Sign-up form
Make both inputs controlled. The button is disabled until the email contains @ and the password has at least 6 characters. On submit, replace the form with "Welcome, email!".
export default function App() {
// TODO: email, password and submitted state; validation; submit handler
return (
<form>
<input type="email" placeholder="Email" /><br />
<input type="password" placeholder="Password (6+ chars)" /><br />
<button>Sign up</button>
</form>
);
}Show solution
import { useState } from 'react';
export default function App() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [submitted, setSubmitted] = useState(false);
const valid = email.includes('@') && password.length >= 6;
if (submitted) return <p>Welcome, {email}!</p>;
return (
<form onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }}>
<input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /><br />
<input type="password" placeholder="Password (6+ chars)" value={password} onChange={(e) => setPassword(e.target.value)} /><br />
<button disabled={!valid}>Sign up</button>
</form>
);
}Exercise 6: Countdown timer
Build a 10-second countdown with Start, Pause and Reset. When it reaches 0, show "⏰ Time's up!" and stop. Make sure no interval keeps running after pausing.
import { useState } from 'react';
export default function App() {
const [seconds, setSeconds] = useState(10);
// TODO: running state + an effect that ticks every second while running
return (
<div>
<p style={{ fontSize: 36, margin: 0 }}>{seconds}</p>
<button>Start</button> <button>Pause</button> <button>Reset</button>
</div>
);
}Show solution
import { useEffect, useState } from 'react';
export default function App() {
const [seconds, setSeconds] = useState(10);
const [running, setRunning] = useState(false);
useEffect(() => {
if (!running) return;
const id = setInterval(() => setSeconds((s) => Math.max(0, s - 1)), 1000);
return () => clearInterval(id);
}, [running]);
useEffect(() => {
if (seconds === 0) setRunning(false); // stop automatically at zero
}, [seconds]);
return (
<div>
<p style={{ fontSize: 36, margin: 0 }}>{seconds}</p>
{seconds === 0 && <p>⏰ Time's up!</p>}
<button onClick={() => setRunning(true)} disabled={running || seconds === 0}>Start</button>{' '}
<button onClick={() => setRunning(false)} disabled={!running}>Pause</button>{' '}
<button onClick={() => { setRunning(false); setSeconds(10); }}>Reset</button>
</div>
);
}Exercise 7: Theme switcher with context
Header and Content should read the theme from a ThemeContext instead of a prop. A button in Header toggles between light and dark.
import { useState } from 'react';
const STYLES = {
light: { background: '#fff', color: '#222' },
dark: { background: '#222', color: '#eee' },
};
// TODO: create ThemeContext; Header and Content should use useContext
function Header() {
return <header style={{ ...STYLES.light, padding: 8, borderBottom: '1px solid #888' }}>My site <button>Toggle</button></header>;
}
function Content() {
return <main style={{ ...STYLES.light, padding: 8 }}>Hello from the content area.</main>;
}
export default function App() {
return (
<div style={{ border: '1px solid #888', width: 300 }}>
<Header />
<Content />
</div>
);
}Show solution
import { createContext, useContext, useState } from 'react';
const STYLES = {
light: { background: '#fff', color: '#222' },
dark: { background: '#222', color: '#eee' },
};
const ThemeContext = createContext(null);
function Header() {
const { theme, toggle } = useContext(ThemeContext);
return (
<header style={{ ...STYLES[theme], padding: 8, borderBottom: '1px solid #888' }}>
My site <button onClick={toggle}>Toggle</button>
</header>
);
}
function Content() {
const { theme } = useContext(ThemeContext);
return <main style={{ ...STYLES[theme], padding: 8 }}>Hello from the content area.</main>;
}
export default function App() {
const [theme, setTheme] = useState('light');
const toggle = () => setTheme((t) => (t === 'light' ? 'dark' : 'light'));
return (
<ThemeContext value={{ theme, toggle }}>
<div style={{ border: '1px solid #888', width: 300 }}>
<Header />
<Content />
</div>
</ThemeContext>
);
}Exercise 8: Shopping cart with useReducer
Implement cartReducer with the actions add (increase quantity or insert with qty: 1), decrement (remove the line when quantity hits 0) and clear. Show the total price — computed, not stored.
import { useReducer } from 'react';
const PRODUCTS = [
{ id: 'pen', name: 'Pen', price: 2 },
{ id: 'book', name: 'Notebook', price: 5 },
{ id: 'bag', name: 'Bag', price: 25 },
];
function cartReducer(cart, action) {
// TODO: handle 'add', 'decrement', 'clear'
return cart;
}
export default function App() {
const [cart, dispatch] = useReducer(cartReducer, []);
return (
<div>
{PRODUCTS.map((p) => (
<button key={p.id} onClick={() => dispatch({ type: 'add', product: p })} style={{ marginRight: 4 }}>
+ {p.name} (${p.price})
</button>
))}
<ul>{cart.map((line) => <li key={line.id}>{line.qty} × {line.name}</li>)}</ul>
<p>Total: $0</p>
</div>
);
}Show solution
import { useReducer } from 'react';
const PRODUCTS = [
{ id: 'pen', name: 'Pen', price: 2 },
{ id: 'book', name: 'Notebook', price: 5 },
{ id: 'bag', name: 'Bag', price: 25 },
];
function cartReducer(cart, action) {
switch (action.type) {
case 'add': {
const line = cart.find((l) => l.id === action.product.id);
if (line) return cart.map((l) => (l.id === line.id ? { ...l, qty: l.qty + 1 } : l));
return [...cart, { ...action.product, qty: 1 }];
}
case 'decrement':
return cart
.map((l) => (l.id === action.id ? { ...l, qty: l.qty - 1 } : l))
.filter((l) => l.qty > 0);
case 'clear':
return [];
default:
return cart;
}
}
export default function App() {
const [cart, dispatch] = useReducer(cartReducer, []);
const total = cart.reduce((sum, l) => sum + l.qty * l.price, 0);
return (
<div>
{PRODUCTS.map((p) => (
<button key={p.id} onClick={() => dispatch({ type: 'add', product: p })} style={{ marginRight: 4 }}>
+ {p.name} (${p.price})
</button>
))}
<ul>
{cart.map((line) => (
<li key={line.id}>
{line.qty} × {line.name} <button onClick={() => dispatch({ type: 'decrement', id: line.id })}>−</button>
</li>
))}
</ul>
<p>Total: ${total}</p>
{cart.length > 0 && <button onClick={() => dispatch({ type: 'clear' })}>Clear cart</button>}
</div>
);
}Exercise 9: A useToggle custom hook
Write useToggle(initial) that returns [value, toggle], then use it for three independent settings.
import { useState } from 'react';
// TODO: write useToggle and use it below instead of the hard-coded values
export default function App() {
const wifi = true;
const sound = false;
const location = true;
return (
<ul style={{ listStyle: 'none', padding: 0 }}>
<li>📶 Wi-Fi: {wifi ? 'on' : 'off'} <button>toggle</button></li>
<li>🔊 Sound: {sound ? 'on' : 'off'} <button>toggle</button></li>
<li>📍 Location: {location ? 'on' : 'off'} <button>toggle</button></li>
</ul>
);
}Show solution
import { useCallback, useState } from 'react';
function useToggle(initial = false) {
const [value, setValue] = useState(initial);
const toggle = useCallback(() => setValue((v) => !v), []);
return [value, toggle];
}
export default function App() {
const [wifi, toggleWifi] = useToggle(true);
const [sound, toggleSound] = useToggle(false);
const [location, toggleLocation] = useToggle(true);
return (
<ul style={{ listStyle: 'none', padding: 0 }}>
<li>📶 Wi-Fi: {wifi ? 'on' : 'off'} <button onClick={toggleWifi}>toggle</button></li>
<li>🔊 Sound: {sound ? 'on' : 'off'} <button onClick={toggleSound}>toggle</button></li>
<li>📍 Location: {location ? 'on' : 'off'} <button onClick={toggleLocation}>toggle</button></li>
</ul>
);
}Test yourself
In the Like button solution, why is likes computed instead of stored in state?
- State can't hold numbers
- It can be derived from
liked, so storing it would risk inconsistency - Computed values are faster to update
- useState only allows one variable per component
In the countdown solution, why does the effect return () => clearInterval(id)?
- To restart the timer
- To stop the interval when pausing or unmounting
- To reset seconds to 10
- It's optional decoration
Which decrement implementation correctly removes a line at quantity 0 without mutating?
- line.qty--; return cart
- cart.splice(index, 1)
- cart.map(...qty - 1).filter(l => l.qty > 0)
- delete cart[index]