Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 132 ยท Practice and Review

Practice Problems: Components, Props and State

15 graded React practice problems on components, props, lists, conditional rendering and state, each with a runnable starter, a hint and a verified solution you can run in your browser.

Reading about React teaches you the vocabulary. Writing components teaches you the language. This page gives you 15 small problems that move from "render a prop" to "lift state into a parent", in roughly increasing difficulty. Each one trains a skill you will use every day, and none needs anything beyond the first three chapters of this tutorial.

Every problem has the same four parts:

  1. A task that says what the finished component must do.
  2. A live starter that runs as given but does the wrong thing. Edit it until the result matches the task.
  3. A hint you can open when you are stuck.
  4. A solution, also runnable, with a short explanation of the idea behind it.

Try each problem for at least five minutes before you open the hint, and read the hint before the solution. Struggling is where the learning happens. If a topic feels unfamiliar, the lessons are linked in each section: props, conditional rendering, lists and keys, useState, state updates, forms and inputs and lifting state up.

The editor loads the React 19 development build, so mistakes produce real warnings in the console panel under the preview (a missing key, for example). Read them: they are often the whole answer. The preview runs in a sandbox, so use in-memory state only; there is no localStorage here.

A few habits will help across all 15 problems:

  • Say what the state is before you write code. What is the smallest set of values that can describe the screen? Everything else should be computed while rendering.
  • Never change state in place. Create a new array or object, then pass it to the setter.
  • Give every list item a stable key taken from the data, not from the position.
  • Run the example after every small change. React's error messages are specific, so short feedback loops are fast.

Components and props

These four problems practise props, children and conditional rendering.

1. A greeting with a default (Easy)

Greeting should render Hello, <name>!. When no name prop is passed, it should say Hello, stranger!. Use destructuring in the parameter list.

Problem 1: A greeting with a default
Show hint

A component receives one object, props. Destructure it in the parameter list, function Greeting({ name }), and give the property a default with =: { name = 'stranger' }. The default applies when the prop is undefined, which is what you get when it is not passed at all.

Show solution
Solution 1: A greeting with a default

Default values in the parameter list are plain JavaScript destructuring defaults. They are the idiomatic way to give a prop a fallback, and they keep the fallback next to the place where the prop is used.

2. A badge with a tone and children (Easy)

Build Badge. It renders a <span> whose text is its children, and whose background colour comes from a tone prop: info (default), success or danger. Use the COLORS lookup object, and also set a data-tone attribute so the tone is visible in the markup.

Problem 2: A badge with a tone
Show hint

Whatever you put between the opening and closing tags of <Badge> arrives as props.children. Destructure { tone = 'info', children } and render inside the span. For the colour, index the lookup object: COLORS[tone].

Show solution
Solution 2: A badge with a tone

children is just another prop, which is why a component can wrap arbitrary content. The tone is data, and the lookup object keeps styling decisions out of a chain of if statements.

3. A product list with a total (Easy)

Render PRODUCTS as a <ul> with one <li> per product, formatted like Notebook - $4.50, followed by a paragraph Total: $44.70. Each list item needs a key. Compute the total while rendering; do not store it anywhere.

Problem 3: A product list with a total
Show hint

products.map((product) => <li key={product.id}>...</li>) produces the items. Number#toFixed(2) gives two decimals. For the total, products.reduce((sum, product) => sum + product.price, 0) is a good fit.

Show solution
Solution 3: A product list with a total

The $ before { is literal text in JSX; the braces open an expression. The key is the product id, a stable identity. The total is derived data, so it is recomputed on every render and can never disagree with the list.

4. Pluralised inbox message (Medium)

Inbox receives a count prop. Render No new messages for 0, 1 new message for 1 and N new messages for anything else. Bonus: also render a red Clear button only when the count is above zero, without ever printing a stray 0.

Problem 4: Pluralised inbox message
Show hint

Compute the label before the return with an ordinary if/else or a ternary. For the button, {count && ...} is the trap: when count is 0, the expression evaluates to the number 0, and React renders numbers. Turn the left side into a real boolean: count > 0 && ....

Show solution
Solution 4: Pluralised inbox message

Plain JavaScript before the return is often the clearest way to choose between several outputs. In the starter, the zero case printed a literal 0 next to the text, because 0 && x evaluates to 0, and React renders numbers. false, null and undefined render nothing; 0 does not.

State and events

The next problems use useState, events and state updates. Remember: state is a snapshot, and you replace it rather than edit it.

5. A counter that cannot go below zero (Easy)

Make the counter work. + adds one, - subtracts one and is disabled at 0, and Reset returns to 0.

Problem 5: A counter that stops at zero
Show hint

Replace the constant with const [count, setCount] = useState(0). Each button gets an onClick handler. Pass a function, not the result of calling one: onClick={() => setCount(count + 1)}. The disabled attribute takes a boolean: disabled={count === 0}.

Show solution
Solution 5: A counter that stops at zero

Disabling the button makes the invalid state impossible to reach, which is better than letting it happen and correcting it afterwards. Each click handler is a closure over this render's count.

6. Show and hide a password (Easy)

Build PasswordField: a controlled text input plus a Show password checkbox. While the box is unchecked the input has type="password"; when checked, type="text". Under the field print Length: N, computed from the current value.

Problem 6: Show and hide a password
Show hint

Two pieces of state: the text (a string) and a boolean for visibility. The input is controlled: value={password} and onChange={(event) => setPassword(event.target.value)}. The checkbox uses checked and reads event.target.checked. The length is derived: do not keep it in state.

Show solution
Solution 6: Show and hide a password

Notice that changing type does not lose what you typed: the text lives in React state, not only in the DOM node. The length is a pure function of password, so it is computed, not stored.

7. Add items to a list (Medium)

Finish the todo list. Submitting the form should append a new todo with the typed title, ignore blank input (spaces only count as blank), and clear the field. Give every todo a unique id.

Problem 7: Add items to a list
Show hint

Pull the setter out of the array: const [todos, setTodos] = useState(...). In the handler, trim the title; if it is empty, return. Otherwise setTodos([...todos, { id: nextId, title: trimmed }]). For ids you can keep a nextId in state, or use the largest existing id plus one. Finally setTitle('').

Show solution
Solution 7: Add items to a list

[...todos, newItem] builds a new array; todos.push(newItem) would mutate the old one and React would not see a change. Using the form's onSubmit (rather than a click handler on the button) means the Enter key works too.

8. Remove an item from a list (Medium)

Each shopping item has a Remove button. Clicking it should delete that item only. The list must keep working after several removals.

Problem 8: Remove an item from a list
Show hint

Array#filter returns a new array containing only the elements for which the callback returns true. Keep everything except the clicked id: items.filter((item) => item.id !== id). Pass the id through a small arrow function: onClick={() => remove(item.id)}.

Show solution
Solution 8: Remove an item from a list

Removing by id rather than by array index is what makes this safe. The stable key also means React keeps the remaining <li> elements and deletes only one DOM node.

9. Update one field of an object in state (Medium)

The profile form keeps name and city in a single object. Typing in either input must update only that field. Use one change handler for both inputs and print Ada lives in London under the form, built from the state.

Problem 9: Update one field of an object
Show hint

Give both inputs the same handler. Inside it, event.target.name tells you which field changed and event.target.value has the new text. Copy the old object with spread and override one key using a computed property: { ...profile, [event.target.name]: event.target.value }.

Show solution
Solution 9: Update one field of an object

If you wrote setProfile({ [event.target.name]: event.target.value }), the other field would vanish: setProfile replaces the whole value, it does not merge like the old class setState. See objects and arrays in state.

10. Fix the "Add 3" button (Medium)

The button calls setCount(count + 1) three times, but each click only adds 1. Fix it so one click adds 3. Do not change the number of setCount calls: the point is to understand why they were not adding up.

Problem 10: Fix the Add 3 button
Show hint

Within one event handler, count is a snapshot: it is 0 on all three lines, so you queue "set to 1" three times. Pass an updater function instead, a function that receives the latest queued value and returns the next one: setCount((current) => current + 1).

Show solution
Solution 10: Fix the Add 3 button

React queues the three updater functions and runs them in order during the next render, feeding each result into the next: 0, 1, 2, 3. Use an updater whenever the next value depends on the previous one and you may set it more than once before a render. See state updates.

Sharing and deriving state

The last five problems combine ideas: lifting state up, choosing state structure and reusable components with props.

11. Two inputs, one source of truth (Hard)

Celsius and Fahrenheit inputs must stay in sync: typing 100 in Celsius shows 212 in Fahrenheit, and typing 32 in Fahrenheit shows 0 in Celsius. Keep one piece of state in the parent, celsius (a string), and let TemperatureInput be a controlled component that knows nothing about conversion. Round converted values to one decimal. An empty or invalid input should clear the other field.

Problem 11: Two inputs, one source of truth
Show hint

The Fahrenheit field's value is derived: celsius converted, or '' if it is not a number. Its onChange converts back and calls setCelsius. Write two tiny helpers, toFahrenheit(text) and toCelsius(text), that return a string. Check Number.isNaN(Number(text)) and text.trim() === '' before converting, and round with Math.round(value * 10) / 10.

Show solution
Solution 11: Two inputs, one source of truth

There is a single source of truth, celsius, and the other field is computed from it. Two pieces of state for the same quantity would drift apart sooner or later. One small limitation: while you type in Fahrenheit, the value is converted to Celsius and back, so intermediate input like - is cleared. A production version would keep the raw text of whichever field you are editing.

12. Search filter with a result count (Medium)

Filter the fruit list as the user types, ignoring case. Show Showing 2 of 6 above the list. The filtered list must not be stored in state: derive it.

Problem 12: Search filter with a count
Show hint

Before the return, compute const visible = FRUITS.filter((fruit) => fruit.toLowerCase().includes(query.trim().toLowerCase())). Render visible instead of FRUITS, and print visible.length and FRUITS.length in the counter.

Show solution
Solution 12: Search filter with a count

Typing ap leaves Apple, Apricot and Grape (it contains "ap" too), so the counter reads Showing 3 of 6. The only state is what the user typed; everything else follows from it. This is the pattern from choosing state structure: store the minimum, compute the rest.

13. A star rating component (Hard)

Build a reusable StarRating. Props: value (0 to 5) and onChange(newValue). It renders five buttons, filled star (โ˜…) for positions up to value, empty (โ˜†) after. Each button has an accessible name like 3 stars (1 star for the first). The parent owns the state and prints Rating: N.

Problem 13: A star rating component
Show hint

Generate the buttons from [1, 2, 3, 4, 5].map((star) => ...). Each button gets key={star}, aria-label, and onClick={() => onChange(star)}. The glyph is star <= value ? 'โ˜…' : 'โ˜†'. The component has no state of its own: it is fully controlled by its props.

Show solution
Solution 13: A star rating component

A controlled component gets its value and a change callback from the parent, which is exactly how the built-in <input> works. Because the star glyphs are not meaningful to a screen reader, the aria-label provides the real name. For deeper treatment see controlled and uncontrolled components and accessibility.

14. An accordion that opens one section at a time (Hard)

Opening a section should close the one that was open. Clicking an open section closes it. Keep a single openId in the parent Accordion; Section receives title, isOpen and onToggle, and its header button sets aria-expanded.

Problem 14: A one-at-a-time accordion
Show hint

Each Section keeping its own open flag is why they do not coordinate. Move the state up to Accordion: const [openId, setOpenId] = useState(null). Pass isOpen={openId === item.id} and onToggle={() => setOpenId(openId === item.id ? null : item.id)}. Put the sections in an array and map over it.

Show solution
Solution 14: A one-at-a-time accordion

When siblings need to agree about something, the state belongs in their closest common parent. Section became a simple presentational component: it shows what it is told. Storing the id of the open section (instead of a boolean per section) makes "only one open" true by construction.

15. Sort without mutating (Hard)

The Sort A-Z button is supposed to toggle between the original order and alphabetical order. The starter calls names.sort() on the state array, which sorts it in place and then hands React the very same array, so the list on screen does not change when you click. Fix it: keep a boolean sorted in state and derive the displayed array from a copy.

Problem 15: Sort without mutating
Show hint

Array#sort sorts in place, and React bails out when setNames receives the very same array object. Keep names constant (it can be a plain const outside the component), add const [sorted, setSorted] = useState(false), and compute const shown = sorted ? [...names].sort() : names. The button label can read Original order while sorted.

Show solution
Solution 15: Sort without mutating

The sorted order is derived data; only the user's choice is state. That also makes "go back to the original order" free, because the original array was never touched. Modern JavaScript offers toSorted(), which returns a sorted copy, but [...array].sort() works everywhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component renders {items.length && <List items={items} />} and items is empty. What appears on the page?

    items.length is 0, so the && expression evaluates to 0, and React renders numbers. Use items.length > 0 && ... so the left side is a real boolean.
  2. 2. Why does calling setCount(count + 1) three times in one handler add only 1?

    Within one render, count is a fixed value. All three calls queue 'set to count + 1' with the same count. Updater functions such as setCount((current) => current + 1) chain correctly.
  3. 3. Two sibling components must always show the same value. Where should the state live?

    Lifting state up to the closest common parent gives a single source of truth. The children receive the value and callbacks as props.
  4. 4. Which of these should usually NOT be stored in state?

    A filtered list can be computed from the full list and the filter during render. Storing it creates a second copy that can fall out of date.
  5. 5. What does setProfile({ city: 'Paris' }) do to a profile object that also has a name field?

    State setters replace the value. Copy the old fields yourself with spread: setProfile({ ...profile, city: 'Paris' }).

Summary

  • Props flow down and are read-only; destructure them in the parameter list and give optional ones a default.
  • children is a prop, so components can wrap arbitrary content.
  • Guard && with a real boolean (count > 0 && ...) so a stray 0 never reaches the page.
  • Lists need a stable key from the data (an id), never the array index for lists that change.
  • State is a snapshot. Replace objects and arrays instead of mutating them, and use updater functions when the next value depends on the previous one.
  • Store the smallest state that describes the screen and derive everything else during render: filtered lists, counts, totals, sorted copies.
  • When components need to agree, lift the state to their closest common parent.

Next: Practice Problems: Hooks, Forms and Patterns