Tutorials Logic, IN info@tutorialslogic.com

React useState Hook State Management

What Is State?

State is data stored inside a component that can change over time. When state changes, React re-renders the component so the UI shows the latest value. State is what makes React interfaces interactive.

Examples of state include a counter value, search text, whether a modal is open, form input values, selected tabs, and fetched data that must be displayed on the page.

State vs Props

Feature Props State
Where it comes from Passed from parent Stored inside the component
Can it change? Not by the child Yes, through a state setter
Main purpose Receive external input Store changing local data

Adding State with useState

The useState hook adds state to function components. It returns two values: the current state and a function used to update that state.

Basic useState Example

Basic useState Example
import { useState } from 'react'

function Counter() {
    const [count, setCount] = useState(0)

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

Updating State Correctly

When the next state depends on the previous state, use the functional form of the setter. This avoids stale values during rapid updates.

Updating State Correctly - JSX Example

Updating State Correctly - JSX Example
setCount(previousCount => previousCount + 1)

Multiple State Values

A component can have more than one piece of state. Each piece should represent one meaningful changing value.

Multiple State Values - JSX Example

Multiple State Values - JSX Example
const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [isOnline, setIsOnline] = useState(false)

State with Objects

When state is an object, remember to copy the old object before changing a single field. Unlike class component state, React does not merge object state automatically in function components.

State with Objects - JSX Example

State with Objects - JSX Example
const [user, setUser] = useState({ name: 'Aman', city: 'Delhi' })

function changeCity() {
    setUser(current => ({
        ...current,
        city: 'Mumbai'
    }))
}

State with Arrays

Arrays in state should also be updated immutably. Instead of changing the existing array directly, create a new array with methods such as map, filter, or the spread operator.

State with Arrays - JSX Example

State with Arrays - JSX Example
const [items, setItems] = useState(['HTML', 'CSS'])

function addItem() {
    setItems(current => [...current, 'React'])
}

function removeItem(itemToRemove) {
    setItems(current => current.filter(item => item !== itemToRemove))
}

Important State Rules

  • Never change state directly
  • Always use the setter returned by useState
  • Use a new object or array when updating complex values
  • Keep state as small and focused as possible

How to Decide What Should Be State

A value should usually be state if it changes over time and its change should update the UI. If a value never changes or can be calculated directly from existing props and state, it may not need its own state.

State Failure Cases

Mistake Why it is a problem Better approach
Changing state directly React may not update correctly Always use the setter function
Storing derived values as extra state Creates duplication and sync bugs Compute derived values during render when possible
Putting too much unrelated data in one state object Makes updates harder to reason about Split state by concern when it improves clarity
Forgetting to copy arrays or objects Mutates existing state and breaks predictability Use spread, map, filter, or structured updates

Best Practices

  • Use state only for values that actually change and affect rendering
  • Keep state close to the component that needs it
  • Use functional updates when the next value depends on the previous one
  • Update objects and arrays immutably
  • Do not duplicate data in multiple state variables unless there is a clear reason

Summary

State is what makes React components dynamic. It allows components to respond to user input, fetched data, and application events. Once you understand how to create, update, and organize state correctly, building interactive React interfaces becomes much easier and more predictable.

State Updates Form a Queue, Not Immediate Assignments

Calling a state setter requests another render. The running event handler continues with the state snapshot captured for the current render, so reading the variable immediately after setting it returns the old snapshot. When the next value depends on the previous value, pass an updater function so React can apply queued updates in order.

React batches compatible updates to avoid unnecessary renders. Do not depend on an intermediate render between setters. Keep render pure, perform event-driven changes in handlers, and use effects only to synchronize with an external system rather than to calculate state that could be derived during render.

Place State at the Smallest Shared Owner

Store one source of truth and derive filtered, counted, or formatted values instead of synchronizing copies. Lift state to the nearest common owner when siblings must coordinate, and preserve local state when no outside component needs to control it. A stable key determines whether React preserves or resets state at a position.

Use a reducer when transitions involve several fields or named events, not merely because an object is large. Test initialization, each transition, reset, stale asynchronous results, and rapid repeated input. For server data, prefer a cache designed for request status and invalidation over duplicating remote state in unrelated components.

Before you move on

React useState Hook State Management Mastery Check

4 checks
  • State is data stored inside a component that can change over time.
  • When state changes, React re-renders the component so the UI shows the latest value.
  • State is what makes React interfaces interactive.
  • The useState hook adds state to function components.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.