Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 132 ยท Practice and Review

Practice Problems: Hooks, Forms and Patterns

15 harder React practice problems on effects, refs, reducers, custom hooks, context, forms, actions, memoization, race conditions, portals and optimistic updates, with verified solutions.

The first set of problems was about the core loop: props in, state, events, render. This set is about everything that surrounds that loop in real applications: talking to the outside world with effects, remembering things without rendering (refs), organising complicated state (reducers), reusing logic (custom hooks), sharing data (context), handling forms and actions, avoiding wasted work (memo) and handling asynchronous timing (async patterns).

The format is the same as before. Every problem has a task, a live starter that runs but is incomplete or buggy, a hint, and a verified solution that you can run and edit. The examples write to the console panel where that helps you see what React is doing, so keep it open.

The editor runs the React 19 development build, without <StrictMode> unless a program adds it. So effects run once on mount in these examples. If you wrap your own code in <StrictMode>, React will deliberately mount, unmount and mount again to expose missing cleanup, and you will see doubled log lines. That is a feature, not a bug.

Some tips for this set:

  • An effect is for synchronising with something outside React: the document title, a timer, a subscription, a request. If you are only transforming data you already have, compute it during render.
  • Every effect that starts something should know how to stop it. Return a cleanup function.
  • Dependencies are not a tuning knob. List every reactive value the effect reads; if that causes trouble, change the code, not the list.
  • Timing examples use short delays (50 to 250 ms) so you do not have to wait. Real servers are slower, which makes the bugs worse, not better.

Effects and refs

1. Sync the document title (Easy)

Every time the click count changes, the browser tab title should read Clicks: N. This is a textbook effect: the document is outside React, and the title must stay in step with state.

Problem 1: Sync the document title
Show hint

Import useEffect and call it inside the component: useEffect(() => { document.title = ... }, [count]). The dependency array lists the value the effect reads, so the effect re-runs only when count changes. Setting a title needs no cleanup.

Show solution
Solution 1: Sync the document title

React renders first, then commits to the DOM, and only then runs your effect. The title therefore changes right after the new number appears. See useEffect and effect dependencies.

2. A stopwatch that really stops (Medium)

The starter's Start/Stop button flips a flag, but the interval is never cleared, so ticks keep increasing after Stop. Fix the effect so the interval exists only while running. The console should log interval started and interval cleared as you toggle.

Problem 2: A stopwatch that really stops
Show hint

setInterval returns an id. Keep it in a local variable inside the effect and return a cleanup function that calls clearInterval(id). React runs the cleanup before the next run of the effect (when running changes) and when the component unmounts. When running is false, the effect should do nothing and return early.

Show solution
Solution 2: A stopwatch that really stops

The updater form setTicks((current) => current + 1) matters here: the interval callback was created in one render, so a plain ticks + 1 would use a stale ticks. Cleanup is the mirror image of setup. See effect cleanup.

3. Focus with a ref (Easy)

A Clear and focus button should empty the text box and put the cursor back in it. Use a ref to reach the input element. Do not use document.querySelector.

Problem 3: Focus with a ref
Show hint

const inputRef = useRef(null), then <input ref={inputRef} />. After React commits, inputRef.current is the DOM node. Call inputRef.current.focus() inside the event handler. Refs are for things you do in handlers or effects; never read or write ref.current while rendering.

Show solution
Solution 3: Focus with a ref

A ref is an escape hatch: a box whose contents survive renders and whose changes do not trigger one. Use it for imperative DOM calls such as focus(), scrollIntoView() and measuring. See useRef.

Reducers, custom hooks and context

4. A shopping cart reducer (Medium)

Implement cartReducer. The actions are { type: 'increment', id }, { type: 'decrement', id } (when the quantity reaches 0 the item is removed) and { type: 'clear' }. The reducer must be a pure function and must return a new array.

Problem 4: A shopping cart reducer
Show hint

Use a switch (action.type). increment and decrement are both cart.map(...) returning a copy of the matching line with a new qty. After decrement, finish with .filter((line) => line.qty > 0). clear returns []. For unknown actions, throw an error so typos fail loudly.

Show solution
Solution 4: A shopping cart reducer

All the rules about how the cart changes live in one function that is easy to test without React. Components only describe what happened by dispatching an action. See reducers.

5. Extract a useToggle hook (Easy)

Two components each have their own on/off state. Move the repeated logic into a custom hook useToggle(initial) that returns [value, toggle]. Each call to the hook gets its own independent state.

Problem 5: Extract a useToggle hook
Show hint

A custom hook is an ordinary function whose name starts with use and that calls other hooks. Inside, call useState(initial) and return the value plus a function that flips it with an updater: setValue((current) => !current). Because the hook calls useState, every component that calls useToggle gets its own separate state.

Show solution
Solution 5: Extract a useToggle hook

A custom hook shares logic, not state. useCallback keeps toggle the same function between renders, which is a courtesy to components that receive it as a prop. See custom hooks.

6. A debounced value hook (Hard)

Write useDebouncedValue(value, delay): it returns the latest value, but only after the value has stopped changing for delay ms. The app logs search: <text> each time the debounced value changes, so quick typing produces few log lines instead of one per keystroke.

Problem 6: A debounced value hook
Show hint

Inside the hook keep const [debounced, setDebounced] = useState(value). An effect depending on [value, delay] starts setTimeout(() => setDebounced(value), delay) and returns () => clearTimeout(timer). Each new keystroke runs the cleanup first, which cancels the pending timer, so only the last value survives.

Show solution
Solution 6: A debounced value hook

On the first render the debounced value equals the initial text, so you see one log line (search: with nothing after it) at mount. Type two characters in quick succession and wait: you get a single further log line with the final text. Without the cleanup every keystroke's timer would fire and the final value would be set repeatedly in sequence.

7. Theme with context (Medium)

Panel is deep in the tree and must show the current theme without receiving it through props. Keep the theme in App, provide it with a context, and read it in Panel with useContext. A button in App toggles between light and dark.

Problem 7: Theme with context
Show hint

Wrap <Layout /> in <ThemeContext value={theme}>...</ThemeContext>. In React 19 the context object itself is the provider, so you no longer write .Provider. In Panel, replace the constant with const theme = useContext(ThemeContext). Layout stays untouched: that is the whole point.

Show solution
Solution 7: Theme with context

Context removes "prop drilling": components between the provider and the consumer do not need to know the value exists. When theme changes, every component that reads ThemeContext re-renders. See context and context patterns.

Forms and actions

8. A validated sign-up form (Medium)

Finish the controlled sign-up form. On submit, check that the email contains @ and the password has at least 8 characters. Show each error under its field in an element with role="alert". If there are no errors, print Welcome, <email>! instead of the form. Never post anywhere: the sandbox has no server.

Problem 8: A validated sign-up form
Show hint

Write a pure validate(email, password) function that returns an object such as { email: 'Enter a valid email', password: '...' } (empty when everything is fine). Keep the errors in state, set them in handleSubmit, and render {errors.email && <span role="alert">{errors.email}</span>} under each field. If Object.keys(found).length === 0, call setDone(true).

Show solution
Solution 8: A validated sign-up form

Validation is a pure function from values to errors, which makes it trivial to test and reuse. noValidate turns off the browser's own bubbles so you control the messages. Always validate again on the server in a real app; client checks are for convenience. See form validation.

9. A form action with FormData (Medium)

React 19 lets you pass a function to a form's action. React calls it with the form's FormData and then resets an uncontrolled form for you. Use that to build a newsletter box with no useState for the input: after submitting, show Subscribed: <email>.

Problem 9: A form action with FormData
Show hint

Replace onSubmit by action={subscribe}. Define a function subscribe(formData) that calls setMessage with a template string built from formData.get('email'). The name attribute on the input is what puts the value into the FormData. Note there is no event and no preventDefault(): React handles it.

Show solution
Solution 9: A form action with FormData

After the action finishes React resets the uncontrolled form, so the input is empty again. If you need the field to keep its text, use a controlled input or defaultValue plus returned state. See form actions and uncontrolled forms.

10. A pending state with useActionState (Hard)

saveName(previousState, formData) simulates a slow server (100 ms). Wire it up with useActionState so that the button reads Saving... and is disabled while the action runs, an empty name returns the message Name is required, and a good name returns Saved: <name>.

Problem 10: A pending state with useActionState
Show hint

const [state, formAction, isPending] = useActionState(saveName, { message: 'Nothing saved yet' }). Pass formAction to the form's action. Make saveName an async function: await new Promise((resolve) => setTimeout(resolve, 100)), read formData.get('name')?.trim(), and return a new state object. Use isPending for disabled and the button label.

Show solution
Solution 10: A pending state with useActionState

useActionState gives you the last returned state, a wrapped action and a pending flag in one hook. The action receives the previous state as its first argument, which is how multi-step flows and error messages are carried between submissions. See useActionState.

Performance, async and patterns

11. Stop a child from re-rendering (Hard)

Clicking Parent count re-renders App, and with it ProductList, which logs ProductList rendered every time even though its props did not change. Make the list render only when its data actually changes. You need two tools: memo for the component and useCallback for the callback prop.

Problem 11: Stop a child from re-rendering
Show hint

memo(ProductList) skips rendering when all props are shallow-equal to the previous ones. PRODUCTS is defined outside the component, so it is already stable. But handleSelect is a new function on every render of App, which defeats memo. Wrap it in useCallback((product) => setSelected(product), []). The empty array is safe: setSelected is stable and the function reads no other reactive value.

Show solution
Solution 11: Stop a child from re-rendering

Open the console panel and click the count button: with the starter, a line is logged on every click; with the solution, the list renders once at mount and stays quiet. Memoisation is an optimisation, not a requirement; measure first and apply it where renders are genuinely expensive. React Compiler can do this automatically. See memo and useMemo and useCallback.

12. Fix a stale response race (Hard)

Clicking User 1 and then quickly User 2 starts two requests. The first is slow (200 ms) and the second is fast (50 ms), so the old response arrives last and overwrites the right one. Fix the effect so that only the response for the currently selected user is ever shown.

Problem 12: Fix a stale response race
Show hint

Declare let ignore = false; inside the effect, check if (!ignore) before calling setName, and return () => { ignore = true; }. When userId changes, React runs the previous effect's cleanup first, flagging the old request as stale. An AbortController achieves the same for a real fetch; here the promise cannot be cancelled, so we ignore its result.

Show solution
Solution 12: Fix a stale response race

Each effect run owns its own ignore variable through a closure. Cleanup flips it for that run only, so late answers for old ids are dropped. This race is one of the most common real-world data-fetching bugs, and libraries like TanStack Query exist partly to solve it for you. See data fetching and async patterns.

13. Compound Tabs with context (Hard)

Build a tab set from three small parts that work together without prop drilling: Tabs (holds the selected value and provides it), TabButton value="..." (selects its value, aria-selected reflects the state) and TabPanel value="..." (shows its children only when selected).

Problem 13: Compound Tabs with context
Show hint

Create const TabsContext = createContext(null). Tabs holds const [selected, setSelected] = useState(defaultValue) and renders <TabsContext value={{ selected, setSelected }}>. The children call useContext(TabsContext). TabPanel returns null unless selected === value. For a polished version, throw a helpful error if the hooks are used outside Tabs.

Show solution
Solution 13: Compound Tabs with context

This is the compound-component pattern: the parts share implicit state through context, and the user composes them freely, like <select> and <option>. A production tab widget also needs arrow-key navigation and aria-controls; see compound components and accessibility.

14. A modal in a portal (Hard)

Implement Modal({ open, onClose, children }). When open is false it renders nothing. When true it renders a role="dialog" element into document.body with createPortal (not inside the app's container), and pressing Escape calls onClose. The key listener must be removed when the modal closes.

Problem 14: A modal in a portal
Show hint

Import createPortal from react-dom and return createPortal(<div role="dialog">...</div>, document.body). Add a useEffect that only does work when open is true: add document.addEventListener('keydown', handler), where the handler calls onClose() when event.key === 'Escape', and return a cleanup that removes the same handler. Hooks cannot come after an early return, so put the effect before if (!open) return null.

Show solution
Solution 14: A modal in a portal

A portal changes where the DOM nodes go, but not the React tree: the modal still belongs to App, receives context and bubbles events to React parents. That lets it escape overflow: hidden and stacking contexts. A complete modal would also trap focus and restore it on close. See portals.

15. Optimistic messages (Hard)

A chat form sends a message to a slow fake server (150 ms). Make the new message appear immediately with the suffix (sending...), and become a normal message once the server answers. Use useOptimistic inside a form action.

Problem 15: Optimistic messages
Show hint

const [shown, addOptimistic] = useOptimistic(messages, (current, text) => [...current, text + ' (sending...)']). Render shown instead of messages. In the action, call addOptimistic(text) before the await. The real state update that happens after the await must be wrapped in startTransition (imported from react), so React commits it together with the end of the action. Then it discards the optimistic layer and shows the real list. If the request fails, the optimistic message simply disappears.

Show solution
Solution 15: Optimistic messages

We recorded every DOM change of the list while sending hi. With startTransition the list goes from Welcome! to hi (sending...) and then to the plain hi. Without it, we also saw an in-between frame showing hi twice (the real message and the optimistic one) before the optimistic layer was dropped. The optimistic value is temporary: it exists only while the action is pending, and it is built from the real state, so the UI can never get stuck in a made-up state. Index keys are acceptable here only because messages are append-only; in a real chat use ids. See useFormStatus and useOptimistic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An effect starts a setInterval. What must it return so the interval does not keep running after unmount or dependency changes?

    React calls the function returned by the effect before re-running it and on unmount. Clearing the interval there is how you stop the work you started.
  2. 2. Why does an 'ignore' flag in a fetching effect prevent stale data?

    Each run of the effect has its own flag. When dependencies change, cleanup marks the previous run as stale, so its late result never reaches setState.
  3. 3. memo(ProductList) still re-renders every time the parent renders. What is the most likely cause?

    memo compares props shallowly. A function or array created during the parent's render is a new reference each time, so the comparison fails. Stabilise it with useCallback, useMemo or by moving it outside the component.
  4. 4. In React 19, how do you provide a context value to a subtree?

    React 19 lets you render the context object itself as the provider. The older .Provider form still works but is no longer needed.
  5. 5. What does useOptimistic show once the real state has updated?

    The optimistic value is built on top of the real state only while an action is pending. When the action settles, React renders the real state again, which also covers failures.

Summary

  • Use effects to synchronise with the outside world, always return cleanup for anything you start, and list every reactive value in the dependency array.
  • Refs hold values that must survive renders without causing one, and reach DOM nodes for imperative calls such as focus().
  • Reducers centralise complicated update rules in a pure function; custom hooks share logic (not state) between components.
  • Context passes data through the tree without props, and in React 19 you render the context object directly as the provider.
  • Forms can be controlled (state per field) or action-based (action={fn} with FormData); useActionState adds returned state and a pending flag, and useOptimistic shows the expected result instantly.
  • memo skips renders only when props are stable; debouncing and stale-response guards both rely on effect cleanup.
  • Portals move DOM output, not the React tree.

Next: React Interview Questions and Answers