Explain it simply
Explain it simply
This lesson teaches nothing new. It is your chance to write what you learned in the Basic chapter with your own hands. Understanding code you read and producing it at the keyboard are different skills, like watching a video about riding a bicycle versus riding one.
There are three exercises. Task 1 is a Counter with + and - buttons. Task 2 is a Greeting that shows "Hello, name!" when it gets a name prop and "Hello, Guest!" when it does not. Task 3 is a ColorPicker whose red, green and blue buttons change the colour of a box. Try each one yourself before you read the solutions below.
Problem → Why → Solution
The problem: two bugs that show up in first attempts
These are the versions that appear most often on a first try at Task 1 and Task 2. The moment the Counter loads in the browser the screen goes blank, and the console shows a "Too many re-renders" error, before anyone has clicked anything.
The Greeting does not crash, but wherever it is used without a prop, as <Greeting />, it shows "Hello, undefined!". Both pieces of code look almost right, which makes the cause hard to spot.
function Counter() {
const [count, setCount] = useState(0);
// calls setCount while rendering -> render -> setCount -> render ...
return <button onClick={setCount(count + 1)}>{count}</button>;
}
function Greeting({ name }) {
// name is undefined when the prop is left out, not ""
return <h3>{name === "" ? "Hello, Guest!" : `Hello, ${name}!`}</h3>;
}Why does this happen?
{setCount(count + 1)} does not hand over a function; it calls one immediately during render. The state change triggers another render, which calls it again, and so on until React stops the loop. In Greeting, a missing prop is undefined, not "", so the check is false and undefined is pasted into the string.
Core concept: what each exercise checks
The three tasks look simple, but each one tests a basic React rule. Before you look at the solutions, check your own code against the four rules below.
1. State is a snapshot of one render (Task 1)
count does not change inside one render. setCount only asks React for a new value on the next render. Calling setCount(count + 1) twice in one handler adds only 1, because both calls start from the old count; setCount((c) => c + 1) always starts from the latest value.
2. Give event props a function, not a call (Tasks 1 and 3)
onClick={increment} and onClick={() => setColor(c)} both hand over a function that React calls when the click happens. When you need to pass an argument, wrap the call in an arrow function.
3. Think about every shape of "no value" (Task 2)
A missing prop is undefined, name={null} is null, and name="" or name=" " are strings. name?.trim() returns undefined for undefined or null and strips spaces otherwise, so a single truthiness check sends all four cases to "Hello, Guest!".
4. Generate the UI from data (Task 3)
Instead of copy-pasting three buttons, map over the COLORS array. The colour strings are unique, so they work as keys, and adding a colour later means adding one array entry.
Let's model rule 2 in Node. In JSX, onClick is just a property on an object. Writing setCount(count + 1) puts the result of an immediate call into that property, not a function.
// What JSX receives in onClick, modelled with plain objects.
function setCount(value) {
console.log(" setCount called with", value);
}
const count = 0;
console.log("rendering the wrong button:");
const wrong = { onClick: setCount(count + 1) }; // runs right now
console.log(" wrong.onClick is", typeof wrong.onClick);
console.log("rendering the right button:");
const right = { onClick: () => setCount(count + 1) }; // runs later
console.log(" right.onClick is", typeof right.onClick);
console.log("user clicks the right button:");
right.onClick();
// rendering the wrong button:
// setCount called with 1
// wrong.onClick is undefined
// rendering the right button:
// right.onClick is function
// user clicks the right button:
// setCount called with 1Notice that setCount logged its line while the wrong button was being rendered, before any click happened. In a real component that line is a state update, and that is exactly what starts the re-render loop from the problem section.
- Render shows the current state
- A click runs the function you gave
- The handler calls the state setter
- React renders again with new state
Never call a state setter while rendering. State changes belong in event handlers (or effects), not in the render itself.
General pattern
const [value, setValue] = useState(initial);
<button onClick={handleClick}>Label</button>
<button onClick={() => setValue((v) => change(v))}>Label</button>
{condition ? <A /> : <B />}
{hasItems && <List />}
{options.map((opt) => (
<button key={opt} onClick={() => setValue(opt)}>{opt}</button>
))}Declare state, give event props a function, use a ternary for two alternatives and && for show-or-hide, and generate repeated buttons from an array with keys.
Worked solutions: Counter, Greeting and ColorPicker
Compare with this only after writing your own version. The three files are separated by comments, and App.jsx shows them all on one page. Your solution can look different and still be right, as long as it follows the four rules.
// Task 1 - src/components/Counter.jsx
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function decrement() {
setCount((c) => c - 1);
}
function increment() {
setCount((c) => c + 1);
}
return (
<div className="counter">
<button type="button" onClick={decrement} aria-label="Decrease">-</button>
<span>{count}</span>
<button type="button" onClick={increment} aria-label="Increase">+</button>
</div>
);
}
export default Counter;
// Task 2 - src/components/Greeting.jsx
function Greeting({ name }) {
const cleanName = name?.trim();
return <h3>{cleanName ? `Hello, ${cleanName}!` : "Hello, Guest!"}</h3>;
}
export default Greeting;
// Task 3 - src/components/ColorPicker.jsx
import { useState } from "react";
const COLORS = ["red", "green", "blue"];
function ColorPicker() {
const [color, setColor] = useState("lightgray");
return (
<div className="color-picker">
{COLORS.map((c) => (
<button key={c} type="button" onClick={() => setColor(c)}>
{c}
</button>
))}
<div style={{ background: color, height: 100 }} />
<p>Selected: {color}</p>
</div>
);
}
export default ColorPicker;
// src/App.jsx
import Counter from "./components/Counter";
import Greeting from "./components/Greeting";
import ColorPicker from "./components/ColorPicker";
function App() {
return (
<main>
<Counter />
<Greeting name="Mya" />
<Greeting />
<ColorPicker />
</main>
);
}
export default App;Code breakdown
- Updater form for the counter
setCount((c) => c + 1);c is the latest value React holds, so each click adds exactly 1 even if the handler runs several times in a row.
- Passing the handler, not calling it
<button type="button" onClick={increment} aria-label="Increase">+</button>No parentheses after increment, so the function itself is passed. aria-label gives screen readers a word instead of the bare "+" symbol.
- One check for every empty case
const cleanName = name?.trim();Optional chaining (?.) returns undefined instead of throwing when name is undefined or null; for a string it strips the surrounding spaces.
- Ternary chooses the text
<h3>{cleanName ? `Hello, ${cleanName}!` : "Hello, Guest!"}</h3>An empty string and undefined are both falsy, so both get "Hello, Guest!". There are two alternatives, so a ternary fits better than &&.
- Buttons generated from data
<button key={c} type="button" onClick={() => setColor(c)}>Each arrow function remembers its own c, so a click sets that button's colour. key={c} works because colour names are unique.
- Inline style object
<div style={{ background: color, height: 100 }} />The outer braces open a JSX expression and the inner ones are the style object. React turns height: 100 into 100px.
On load the counter shows 0, the two greetings read "Hello, Mya!" and "Hello, Guest!", and the box is lightgray with "Selected: lightgray". Clicking + or - changes the number, and clicking red, green or blue changes the box colour and the "Selected:" text immediately.Predict before you click
After the exercises, rewrite the handler in each of the forms below and predict what one click shows when count starts at 0. Then check in the browser. If a prediction was wrong, reread rule 1.
| Code inside the handler | After one click |
|---|---|
| setCount(count + 1); setCount(count + 1); | 1 (both start from the same snapshot) |
| setCount((c) => c + 1); setCount((c) => c + 1); | 2 (each updater builds on the last) |
| setCount(count + 1); console.log(count); | Console shows 0, the screen shows 1 |
The && and 0 trap
{count && <p>Clicked {count} times</p>} does not render nothing when count is 0; it renders the character "0". React skips false, null and undefined but does render the number 0. Write {count > 0 && ...} so the condition is a real boolean.
In real projects
In real projects
The patterns in these three small components appear in every production app. The Counter becomes a quantity stepper in a shopping cart or the guest-count control on a booking form. The Greeting's fallback logic is what shows "Guest" to a visitor who has not logged in, or the user's initials when there is no profile photo.
The ColorPicker is the seed of size-selector button groups, dashboard tabs and theme switchers. In real apps those groups are built with aria-pressed or radio inputs so they work from the keyboard and screen readers announce the current choice. When the basic pattern is right, those accessibility steps are simple additions. Small, self-contained components like these are also the easiest to test: render one with given props, click a button, and check which text appears.
Common mistakes
Common mistakes
Writing onClick={setCount(count + 1)}
The function runs immediately during render, the state changes, React renders again and calls it again, and the loop ends in a "Too many re-renders" error. Use onClick={() => setCount(count + 1)} or pass a handler name without parentheses.
Checking only name === ""
A missing prop is undefined, so you get "Hello, undefined!"; null and whitespace-only names are possible too. Test the truthiness of name?.trim() to cover every case at once.
Putting a number on the left of &&
{count && ...} prints "0" when count is 0, and {items.length && ...} has the same bug. Turn the condition into a boolean with > 0 or Boolean().
Best practices
Getting the most out of practice
- Struggle with each task for at least fifteen minutes before looking; the place you get stuck is the thing to learn
- Write one component per file and render it from App.jsx with several different props
- Keep the browser console open, because React's warnings usually announce a bug before you notice it
- When you finish, compare with the solution and ask "why?" about every difference
Mini challenge
Practice set 2: logic with limits
Now make the three tasks harder. Before putting anything in a component, write the logic as three pure functions and test them in Node: stepCount keeps the counter between a min and a max, greetingFor handles every shape of name, and nextColor cycles through the colours with a single button.
- stepCount(count, delta, min, max) clamps the result between min and max, so it never drops below 0
- greetingFor returns "Hello, Guest!" for undefined, null, "" and whitespace, and trims real names
- nextColor(current, colors) returns the next colour and wraps from the last back to the first
- When current is not in the list (for example "lightgray"), start from the first colour
function stepCount(count, delta, min, max) {
// TODO: add delta, then keep the result between min and max
}
function greetingFor(name) {
// TODO: only a non-empty string after trim() counts as a name
}
function nextColor(current, colors) {
// TODO: find current's index; move one step forward and wrap around
}
// TODO: simulate clicks + + + + - with limits 0..3 and print each count
// TODO: print greetingFor for "Mya", " Ko Ko ", "", " ", undefined, null
// TODO: start at "lightgray" and print four nextColor stepsExpected: The count after each click (1, 2, 3, 3, 2) and "minus at 0 -> 0", one greeting per name (Guest for everything except Mya and Ko Ko), and finally "lightgray -> red -> green -> blue -> red".
Show hint
Clamp with Math.min(max, Math.max(min, value)). indexOf returns -1 when nothing matches, so (-1 + 1) % length is 0 and you start at the first colour for free. In a component you would write setCount((c) => stepCount(c, 1, 0, 3)).
Show solution
function stepCount(count, delta, min, max) {
return Math.min(max, Math.max(min, count + delta));
}
function greetingFor(name) {
const clean = typeof name === "string" ? name.trim() : "";
return clean ? `Hello, ${clean}!` : "Hello, Guest!";
}
function nextColor(current, colors) {
const index = colors.indexOf(current);
return colors[(index + 1) % colors.length];
}
let count = 0;
const clicks = [+1, +1, +1, +1, -1];
for (const delta of clicks) {
count = stepCount(count, delta, 0, 3);
console.log(`click ${delta > 0 ? "+" : "-"} -> ${count}`);
}
console.log("minus at 0 ->", stepCount(0, -1, 0, 3));
for (const name of ["Mya", " Ko Ko ", "", " ", undefined, null]) {
const label = typeof name === "string" ? JSON.stringify(name) : String(name);
console.log(label, "->", greetingFor(name));
}
const colors = ["red", "green", "blue"];
let color = "lightgray";
const seen = [color];
for (let i = 0; i < 4; i++) {
color = nextColor(color, colors);
seen.push(color);
}
console.log(seen.join(" -> "));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Give event props a function, and wrap it in an arrow function when it needs an argument
- State is a snapshot of one render, so use the updater form when the next value depends on the last
- "No value" can be undefined, null, "" or whitespace, so test the truthiness of name?.trim()
- Keep the left side of && a boolean, and generate repeated buttons from an array with keys
React Documentation — React