🔥 0
0
Lesson 5 of 10 25 min +125 XP

State with useState

State is what makes React components interactive. Unlike props, state can change over time.

Props vs State

PropsState
Passed from parentManaged within component
Read-onlyCan be updated
Like function argumentsLike local variables that trigger re-renders

The useState Hook

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  //     ^        ^             ^
  //     |        |             initial value
  //     |        updater function
  //     current value

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

Rules of useState

  • Call at top level - Not inside loops, conditions, or nested functions
  • Call in React functions - Only in components or custom hooks
  • Use the setter - Never modify state directly: count = 5

State Updates Trigger Re-renders

When you call setCount, React:

  • Updates the state value
  • Re-renders the component
  • Shows the new UI

Try the interactive state examples below!

Props: Passing Data