CodeBlanks Logo Icon CodeBlanks

Summary - useState

Practice state by writing a collapsible accordion component.

Summary - useState

In this group you learned state. useState returns a value and an updater; the value is remembered across renders.

You never mutate state directly; you always call the updater. For updates based on the old value, the function form setN(n => n + 1) is safe.

Several pieces of state live in separate useState calls; related values can be grouped in one object and updated with spread.

Practice useState summary task

Complete the skeleton. Write a Mood component; import useState. Define const [happy, setHappy] = useState(true);. Inside toggle call setHappy(h => !h). Return <button onClick={toggle}>{happy ? "Happy" : "Sad"}</button>. Export it.

Starter code

App.jsx
import { useState } from "react";

// Define Mood here

Sample solution

App.jsx
import { useState } from "react";

function Mood() {
  const [happy, setHappy] = useState(true);
  function toggle() { setHappy(h => !h); }
  return <button onClick={toggle}>{happy ? "Happy" : "Sad"}</button>;
}

export default Mood;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is wrong?

App.jsx
Direct mutation does not update state.
  • useState(0) is the initial value
  • setCount(count + 1) updates
  • count++ updates state Correct answer
  • useState is called at the top

Explanation: count++ is direct mutation; React does not see it.

2 Summary - useState: match the terms

Term Meaning
useState Hook
updater New value
function form Safe increment
spread ...f Object update

All lessons in Beginner