State with useState
State is the heartbeat of interactive React apps — it's data that changes over time and triggers UI re-renders when it does. The useState hook is React's built-in way to add state to functional components. In this chapter you'll learn exactly how to declare state, read it, update it safely, manage arrays and objects in state, and avoid the most common mistakes — with fully runnable code examples throughout.
1. What is State?
In React, state is data that belongs to a component and can change over time. Whenever state changes, React automatically re-renders the component to reflect the latest data in the UI.
Think of state as the component's own private memory. Unlike props (which are read-only inputs from a parent), state is managed inside the component itself and can be changed by the component whenever something happens — a button click, a form input, a timer tick, an API response, and so on.
useState,
persists across renders — React preserves it between function calls.
setCount(newValue))
2. useState Syntax
useState is a React Hook — a special
function that lets you "hook into" React features from functional components. You import it
from 'react' and call it at the top level of
your component (never inside loops or conditionals).
import { useState } from 'react';
// Syntax: const [stateVariable, setterFunction] = useState(initialValue);
function Counter() {
// Declare a state variable "count" with initial value 0
const [count, setCount] = useState(0);
return (
<div>
<p>Count: <strong>{count}</strong></p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}Breaking down the pattern:
useState
returns an array of exactly two items: the current state value and the setter function.
Name them anything — convention is thing /
setThing.
null.
This value is only used on the first render.
isOpen / setIsOpen,
userName / setUserName,
items / setItems.
This makes the relationship immediately clear when reading code.
3. Reading and Updating State
You read state just like any variable: use it directly in JSX expressions or inside functions. You update state by calling the setter — React will then re-run the component with the new value.
import { useState } from 'react';
function LightSwitch() {
const [isOn, setIsOn] = useState(false);
function handleToggle() {
setIsOn(!isOn); // flip between true and false
}
return (
<div>
<p>The light is: <strong>{isOn ? 'ON 💡' : 'OFF 🌑'}</strong></p>
<button onClick={handleToggle}>Toggle Light</button>
</div>
);
}
function NameInput() {
const [name, setName] = useState('');
return (
<div>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Type your name..."
/>
<p>Hello, {name || 'stranger'}!</p>
</div>
);
}setState does not immediately
change the state variable in the current render. The updated value is only available on the
next render. Don't read count right after calling
setCount(count + 1) expecting the new value — use a
functional update instead (see Section 4).
4. Functional Updates — Using Previous State
When your new state depends on the previous state, pass a function to the setter instead of a value. React will call this function with the most up-to-date state value, avoiding stale-state bugs — especially when multiple updates are batched.
// Reading "count" from the closure // can be stale if React batches // multiple state updates const handleClick = () => { setCount(count + 1); // uses closure value setCount(count + 1); // still same "count"! // result: count + 1, not count + 2 };
// Pass a function — React gives // it the latest state value (prev) // each time const handleClick = () => { setCount(prev => prev + 1); // safe setCount(prev => prev + 1); // +2 total ✓ // result: count + 2 };
function Counter() {
const [count, setCount] = useState(0);
// ✅ Use functional update when new state depends on old state
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
const reset = () => setCount(0); // not dependent on prev → direct value ok
const double = () => setCount(prev => prev * 2);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
<button onClick={double}>×2</button>
<button onClick={reset}>Reset</button>
</div>
);
}count + 1,
!isOpen, [...prev, newItem]),
always use the functional form. If the new state is independent of the old (e.g. resetting
to 0 or a hardcoded value), a direct value is fine.
5. Multiple State Variables
You can call useState multiple times in the same
component — each call creates an independent piece of state. This is
usually better than a single object when the values are unrelated.
function UserProfile() {
// Each useState call is independent
const [name, setName] = useState('');
const [age, setAge] = useState(18);
const [isAdmin, setIsAdmin] = useState(false);
const [score, setScore] = useState(0);
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} placeholder="Name" />
<input type="number" value={age} onChange={e => setAge(Number(e.target.value))} />
<label>
<input type="checkbox" checked={isAdmin} onChange={e => setIsAdmin(e.target.checked)} />
Admin
</label>
<p>{name} | Age: {age} | Admin: {isAdmin ? 'Yes' : 'No'} | Score: {score}</p>
</form>
);
}useState calls when the values
change independently. Group them into a single object when they always change together
(e.g. x and y
coordinates
of a draggable element).
6. Objects and Arrays in State
React state can hold any value — including objects and arrays. The key rule is immutability: never mutate the existing value in place. Always create a new object or array and pass it to the setter. React uses reference equality to detect changes — if you mutate in place, it sees the same reference and skips the re-render.
import { useState } from 'react';
// ── Object state ──────────────────────────────────────────────
function UserCard() {
const [user, setUser] = useState({ name: 'Arjun', age: 25, city: 'Vadodara' });
const updateCity = () =>
setUser(prev => ({ ...prev, city: 'Mumbai' })); // spread to preserve other fields
const birthday = () =>
setUser(prev => ({ ...prev, age: prev.age + 1 }));
return (
<div>
<p>{user.name} · {user.age} · {user.city}</p>
<button onClick={updateCity}>Move to Mumbai</button>
<button onClick={birthday}>Birthday 🎂</button>
</div>
);
}
// ── Array state ───────────────────────────────────────────────
function TodoList() {
const [todos, setTodos] = useState(['Buy milk', 'Walk the dog']);
const [input, setInput] = useState('');
// ADD — spread existing + new item
const addTodo = () => {
if (!input.trim()) return;
setTodos(prev => [...prev, input.trim()]);
setInput('');
};
// REMOVE — filter returns a new array
const removeTodo = (index) =>
setTodos(prev => prev.filter((_, i) => i !== index));
return (
<div>
<input value={input} onChange={e => setInput(e.target.value)} />
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo, i) => (
<li key={i}>
{todo} <button onClick={() => removeTodo(i)}>✕</button>
</li>
))}
</ul>
</div>
);
}Quick reference for common immutable array operations:
| Operation | ❌ Mutating (Don't!) | ✅ Immutable (Do this) |
|---|---|---|
| Add item | arr.push(item) |
[...arr, item] |
| Remove item | arr.splice(i, 1) |
arr.filter((_, idx) => idx !== i) |
| Update item | arr[i] = newVal |
arr.map((v, idx) => idx === i ? newVal : v) |
| Sort | arr.sort() |
[...arr].sort() |
| Update object field | obj.field = val |
{ ...obj, field: val } |
7. State vs Props
State and props are both ways for components to have data — but they serve very different purposes. Understanding the difference is fundamental to React architecture.
| Aspect | 🔷 State (useState) | 🔶 Props |
|---|---|---|
| Origin | Defined inside the component | Passed in from a parent component |
| Who controls it? | The component itself | The parent component |
| Mutable? | Yes — via the setter function | No — read-only inside the component |
| Triggers re-render? | Yes — updating state re-renders | Yes — if parent passes new props |
| Use case | Counter value, form input, open/close toggle | User name, theme color, callback functions |
// LikeButton owns its own "likes" state
// It receives a "label" prop from parent
function LikeButton({ label }) { // ← prop (read-only)
const [likes, setLikes] = useState(0); // ← state (mutable internally)
return (
<button onClick={() => setLikes(prev => prev + 1)}>
{label} 👍 {likes}
</button>
);
}
// Parent passes label as prop; each instance has its own state
function App() {
return (
<div>
<LikeButton label="Post A" />
<LikeButton label="Post B" /> {/* independent state */}
</div>
);
}8. Common useState Mistakes
These are the most frequent bugs beginners encounter with useState.
Knowing them now will save you hours of debugging later.
state.name = 'new' or
arr.push(item) bypasses React — no re-render
happens.
Always use the setter with a new value: setState({...state, name: 'new'}).
setCount(5), reading count
in the same function still returns the old value. The new state is only available in the
next render.
Use the functional update form or store the new value in a local variable first.
useState
inside an if block or loop makes the order
unpredictable.
Always call hooks at the top level of your component.
import {'{ useState }'} from 'react'.
Using React.useState also works but requires
importing React.
useEffect, or callbacks.
9. Code It Live — React Playground
The fastest way to master useState is to experiment with
it. Copy any code example from this chapter and paste it into OneCompiler's React IDE — it
supports JSX, Babel, and hooks with zero setup. Click below and start building.
useState(initialValue) returns an array of exactly two items:
- The current state value (starts as
initialValueon the first render) - A setter function used to update the state and trigger a re-render
const [value, setValue] = useState(initial).
Read value in JSX. Call setValue(newValue) to update.
setCount(count + 1)) can be stale if React batches multiple
updates. Passing a function to the setter — setCount(prev => prev + 1)
— guarantees React always provides the latest state value as prev,
making the update correct regardless of batching.
arr.push()?
arr.push(item), you're modifying the same array object in memory
— its reference hasn't changed. React sees the same reference and skips the re-render,
so your UI doesn't update. Always create a new array with
[...arr, item] so React detects the change and re-renders.
- State is a component's private memory — data that changes and drives re-renders.
useState(initial)returns [value, setter] — destructure both at the top of your component.- Calling the setter function is the only correct way to update state — never mutate directly.
- Use functional updates (
prev => prev + 1) whenever the new state depends on the previous one. - Multiple
useStatecalls create independent pieces of state — split or group based on how values change together. - For objects and arrays, always create new copies (spread, filter, map) — mutation breaks React's change detection.
- Props come from outside (read-only); state lives inside (mutable via setter).
- Common pitfalls: calling useState in conditionals, reading state right after setting, and mutating in place.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.