Home / React / Lesson 5

State with useState

Beginner 10 min read Lesson 5 of 11

useState is a Hook: a function you call at the top of a component (not inside loops or conditions). It returns the current value and a setter.

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count}
    </button>
  );
}

Calling setCount queues a re-render with the new value. Do not do count++ and expect the screen to update — React only re-renders when you use the setter (or a parent’s setter).

Objects and arrays

State must be treated as immutable. Copy, then change:

const [student, setStudent] = useState({ name: 'Priya', cgpa: 8.2 });

function bump() {
  setStudent({ ...student, cgpa: student.cgpa + 0.1 });
}

const [items, setItems] = useState(['DS', 'OOP']);
setItems([...items, 'DBMS']);          // add
setItems(items.filter((x) => x !== 'DS')); // remove

If two updates need the previous value, pass a function: setCount(c => c + 1). That avoids stale closures if React batches updates.

Each component instance has its own state. Two <Counter /> on a page do not share count.