React Fundamentals

Lesson 3 of 6

State and Event Handling

Props let data flow in from a parent, state lets a component remember and update its own data over time. The useState hook is how you add state to a function component.

import { useState } from 'react';

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

How it works

  • useState(0) returns a pair, the current value (count) and a setter function (setCount), starting at 0.
  • Calling setCount(...) tells React the value changed, React then re-renders the component with the new value.
  • onClick={() => setCount(count + 1)} attaches an event handler, the same pattern works for onChange, onSubmit, and every other DOM event.

WARNING

Never mutate state directly (count++ or count = count + 1), always go through the setter, or React won't know to re-render.

📝 State Quiz

Passing score: 70%
  1. 1.What does useState(0) return?

  2. 2.Calling the setter function returned by useState triggers a component ____.

  3. 3.You should mutate a state variable directly instead of calling its setter function.