TS PlaygroundLearnReactState with useState
react/beginner

State with useState

Add interactivity to components by managing state with the useState hook.


What is state?

State is data that belongs to a component and can change over time. When state changes, React automatically re-renders the component with the new value.

The useState hook

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

useState(0) returns a pair: the current value (count) and a setter function (setCount). Calling the setter triggers a re-render.

TypeScript and useState

TypeScript infers the type from the initial value. You can also be explicit:

const [name, setName] = useState<string>("");
const [items, setItems] = useState<string[]>([]);

Updating based on previous state

When the new state depends on the old state, pass a function to the setter:

setCount(prev => prev + 1); // always safe

Your task

Build a counter component that:

  1. Starts at 0
  2. Has an Increment button that adds 1
  3. Has a Decrement button that subtracts 1
  4. Has a Reset button that returns to 0
  5. Displays the current count in a <p> element

The tests will check the DOM, so make sure your buttons have the exact text shown above.

import { useState } from "react";

export default function App() {
  // Add state here

  return (
    <div>
      {/* Display the count and add buttons */}
    </div>
  );
}

Click Run Tests to see results
Props & ComponentsEffects with useEffect