Tutorials React JS State with useState
Ch 12 / 46
Chapter 12 Beginner 9 min read React JS

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.

Advertisement
What you'll learn
What is state? — data that changes and drives re-renders
useState syntax — declaring state variables and setter functions
Reading and updating state — setters, batching, and re-renders
Functional updates — using the previous state safely
Multiple state variables — managing separate pieces of state
Objects and arrays in state — immutable update patterns
State vs Props — when to use each
Common useState mistakes and how to avoid them

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.

Private to the Component
State lives inside the component. A parent doesn't know about it and other components can't read or change it directly.
Triggers Re-renders
Calling the setter function schedules a re-render. React re-runs the component function with the new state value and updates the DOM.
Never Mutate Directly
You must always use the setter function — never modify the state variable directly. React relies on the setter to know when to re-render.
Persists Across Renders
React remembers state between renders. Unlike a regular variable, state keeps its value even when the component function re-runs.
Key Distinction A regular JavaScript variable declared inside a component resets to its initial value every time the component re-renders. State, managed by useState, persists across renders — React preserves it between function calls.
① User interaction (click, type, etc.) fires an event handler
↓
② Event handler calls the setter function (e.g. setCount(newValue))
↓
③ React schedules a re-render with the new state value
↓
④ Component function re-runs → returns updated JSX → DOM is patched

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).

jsx — useState declaration pattern
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:

const [count, setCount] Array destructuring. useState returns an array of exactly two items: the current state value and the setter function. Name them anything — convention is thing / setThing.
useState(0) The argument is the initial state. It can be any value: a number, string, boolean, array, object, or even null. This value is only used on the first render.
count The current state value. Read it in JSX or in event handlers. Never assign to it directly.
setCount(newValue) The setter function. Calling it with a new value tells React to re-render the component with that value as the new state.
Naming Convention Always name your state variable and setter as a pair: 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.

jsx — toggle and string state examples
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> ); }
State Updates Are Asynchronous Calling 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.9 / 5 rating
🔥 Most Popular at K2infocom · Vadodara
Frontend Development
Complete Masterclass
Master the full front-end stack — HTML, CSS, JavaScript, React JS, Bootstrap & more. Learn by building 10+ real-world projects. Get certified and job-ready in 3–6 months.
HTML5 & CSS3 JavaScript ES6+ React JS Bootstrap 5 Git & GitHub 5+ Projects Certificate
2,500+Students Trained
10+Live Projects
3–6Months Duration
100%Placement Support
Advertisement

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.

❌ Potentially Buggy
// 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
};
✅ Always Correct
// 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
};
jsx — functional update best practice
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> ); }
Rule of Thumb If your new state is computed from the old state (e.g. 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.

jsx — multiple independent state variables
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> ); }
When to Group State Split state into separate 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).
Advertisement

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.

jsx — immutable object and array state patterns
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
jsx — state vs props in context
// 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.

Mutating state directly 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'}).
Reading state right after setting it After 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.
Calling useState inside loops or conditionals React tracks hooks by call order. Placing useState inside an if block or loop makes the order unpredictable. Always call hooks at the top level of your component.
Forgetting to import useState You must import it: import {'{ useState }'} from 'react'. Using React.useState also works but requires importing React.
Using setState in render (infinite loop) Calling a setter directly in the component body (not inside an event handler or effect) triggers a re-render → which calls the setter again → infinite loop. Always call setters inside event handlers, useEffect, or callbacks.
Free Download
React JS Complete Cheat Sheet — 2026 Edition
Hooks, JSX rules, lifecycle, Redux patterns, Next.js App Router — all on one page.
Download PDF
Advertisement

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.

⚛
Ready to practise useState?
OneCompiler gives you a full React + JSX + Babel environment in your browser. No Node.js, no install — just open, paste, and run.
Let's Code Now  →
React + JSX useState support Babel compiled Opens in new tab Free & no login needed
🚀 Advanced Track · K2infocom
MERN Stack Full-Course — MongoDB · Express · React · Node
Build real-world apps end-to-end. REST APIs, authentication, deployment. Perfect after completing this React series.
MongoDB Express React Node.js
Quick Check — Test Your Understanding
Q1. What does useState return and how do you use it?
✅ Answer
useState(initialValue) returns an array of exactly two items:
  1. The current state value (starts as initialValue on the first render)
  2. A setter function used to update the state and trigger a re-render
You destructure them: const [value, setValue] = useState(initial). Read value in JSX. Call setValue(newValue) to update.
Q2. Why should you use a functional update instead of a direct value?
✅ Answer
When the new state depends on the previous state, using the closure value (e.g. 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.
Q3. Why can't you mutate an array in state with arr.push()?
✅ Answer
React detects state changes by reference equality. When you call 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.
Multiple Choice Questions
MCQ 1
What is the correct way to declare a state variable that starts at 10?
MCQ 2
Which of the following correctly adds an item to an array in state?
MCQ 3
Where must you call useState?
Chapter 12 Summary
  • 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 useState calls 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel