Script Valley
React.js: Complete Course
State and Event HandlingLesson 2.1

useState hook explained with practical examples

useState syntax, state initialization, state variable, setter function, re-render on state change, functional updates, state with different data types

Managing State with useState

State is data that changes over time and causes the UI to update. useState is the hook that adds state to functional components.

Basic Syntax

import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
}

useState returns a tuple: the current state value and a setter function. Calling the setter triggers a re-render with the new value.

Functional Updates

When new state depends on old state, use the functional form to avoid stale closure bugs:

// Unsafe โ€” count may be stale
setCount(count + 1);

// Safe โ€” always uses latest state
setCount(prev => prev + 1);

State With Objects

const [user, setUser] = useState({ name: 'Raj', age: 25 });

// Always spread โ€” never mutate directly
setUser(prev => ({ ...prev, age: 26 }));

Never mutate state directly (state.value = x). React won't detect the change and won't re-render. Always call the setter with a new value or new object.

Up next

How React event handling works

Sign in to track progress

useState hook explained with practical examples โ€” State and Event Handling โ€” React.js: Complete Course โ€” Script Valley โ€” Script Valley