1

useState

Learn how to manage state in React components with the useState hook

Beginner

Core Concepts

  • The useState hook gives your component "memory", without it, your component can't remember anything between renders.
  • When state changes, React automatically re-renders your component to show the new value.
  • It returns an array: [currentValue, updateFunction]
  • When you call the update function, React re-renders automatically
  • The initial value is only used on the first render

Live Demo

0

How It Works

  1. 1
    Component renders with count = 0

    React runs your function and displays the initial value

  2. 2
    User clicks "Increment" button

    The onClick handler fires

  3. 3
    setCount(1) is called

    This tells React "Hey, count changed!"

  4. 4
    React re-renders the component

    Runs your function again, but now count = 1

  5. 5
    UI updates automatically!

    User sees the new value on screen

Code

import { useState } from 'react';

function Counter() {

  // Declare a state variable called "count"
  const [
    count,          // current value
    setCount        // function to update it
  ] = useState(0);  // initiate value to 0

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