TutorialsReactState & Hooks
React

State & Hooks

State is data that a component owns and can change over time. When state changes, React re-renders the component to reflect the new value. You add state with 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)}>+1</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

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

💡

Never mutate state directly (count++). Always use the setter so React knows the state changed and re-renders.

Updating based on previous state

When the new state depends on the old, pass a function to the setter — this avoids bugs from stale values:

setCount((prev) => prev + 1);

State with objects and arrays

Create a new object/array instead of mutating the existing one (spread the old values):

const [user, setUser] = useState({ name: "Priya", age: 28 });

// Update one field immutably
setUser((prev) => ({ ...prev, age: 29 }));

const [items, setItems] = useState([]);
setItems((prev) => [...prev, newItem]); // add
setItems((prev) => prev.filter((i) => i.id !== id)); // remove

What are hooks?

Hooks are functions starting with use that let function components "hook into" React features. Common ones:

  • useState — local state
  • useEffect — side effects (next chapter)
  • useRef — mutable values / DOM references
  • useContext — read shared context
  • useMemo / useCallback — memoization
💡

Rules of Hooks: only call hooks at the top level of a component (never inside conditions, loops, or nested functions), and only from React components or custom hooks.

Watch & Learn

A recommended video to watch alongside this chapter.

More “State & Hooks” videos on YouTube