React State with useState and TypeScript

Learn how useState snapshots work, how TypeScript infers state types, and how to update objects and arrays immutably in React components.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

React state is a snapshot associated with a render, so calling a setter schedules the next render rather than changing the current variable. This guide compares direct and functional updates, shows how to copy objects and arrays, and explains when TypeScript needs an explicit state type for empty or nullable values. It also covers derived data and validating external values before storing them.

React State with useState and TypeScript

Introduction

useState stores a value between renders. Each render sees a snapshot, which explains why setters and immutable updates matter.

This article explains state inference, queued setter updates, and immutable changes to object and array state.

State is a render snapshot

Each handler closes over the state value from the render that created it. Two direct updates in one click therefore read the same count:

function incrementTwice() {
  setCount(count + 1);
  setCount(count + 1);
}

That code adds one, not two. When the next value depends on the previous one, pass updater functions so React applies them in order:

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

The current render still sees its original value. React renders again with the new state after processing the updates.

Let TypeScript infer simple state

TypeScript infers numbers and strings. For state starting empty or null, add a type argument so later values fit.

interface Task {
  id: string;
  done: boolean;
}

const [query, setQuery] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null);
const [tasks, setTasks] = useState<Task[]>([]);

useState<Task[]>([]) types an empty initial list for the values it will later hold. string | null makes the unselected case explicit.

Update objects and arrays immutably

Create a replacement object or array when changing state; do not mutate and reuse the same reference.

interface Settings {
  darkMode: boolean;
}

const [settings, setSettings] = useState<Settings>({ darkMode: false });

function toggleDarkMode() {
  setSettings((current) => ({ ...current, darkMode: !current.darkMode }));
}

For arrays, use methods like map, filter, or spread that return a new array. This map replaces only the matching task.

function toggleTask(taskId: string) {
  setTasks((current) =>
    current.map((task) =>
      task.id === taskId ? { ...task, done: !task.done } : task,
    ),
  );
}

Set a known replacement directly. Use an updater when the new value depends on old state, and copy objects or arrays before changing them. If deep nesting makes updates hard to follow, split the state into smaller pieces.

Update flow

flowchart LR
  A[Current render snapshot] --> B[State setter]
  B --> C[React schedules update]
  C --> D[Component renders again]
  D --> E[New state snapshot]

Trade-Off Table

Update style Useful when Cost
Direct setter value The next value is already known Can use a stale snapshot in calculations
Functional updater New state depends on old state Slightly more syntax
Immutable object copy Updating a few object fields Must copy changed nesting levels
Reducer Many related transitions More setup than simple state needs

Production Failure Scenarios

Two calls to setCount(count + 1) can both use the same snapshot. Use setCount((current) => current + 1) so React applies each to the latest value. Avoid push; mutating an array preserves its reference. A second failure is an update based on a stale object that overwrites a newer field. Use a functional update and copy the current object before changing the relevant property.

Common Pitfalls / Anti-Patterns

Avoid reading state after a setter as if it changed, mutating values, or omitting null from a nullable state type. Do not log every render.

Observability Checklist

  • Track failed saves or unexpected empty data, not every render.
  • Report validation errors with a safe record ID.
  • Keep personal form values out of logs.

Security and Compliance Notes

TypeScript does not validate API data at runtime. Check external values before storing them. Do not put secrets in client state; browser code is visible to users.

When to Use / When NOT to Use

Use useState for values that change locally and affect rendering, such as an open panel or selected option. Keep derived values in render instead of storing a second copy. Consider a reducer when transitions across several related fields need one explicit update path.

Quick Recap Checklist

  • Each render reads a snapshot of state.
  • Setters schedule an update; they do not change the current variable.
  • Use updater functions when the next value depends on the previous one.
  • Copy objects and arrays instead of mutating them.
  • Add explicit types for empty or nullable initial values.

Interview Questions

1. Why does state appear unchanged after calling a setter?

The current call keeps its snapshot. React schedules another render with the updated value.

2. When should you use a functional state update?

Use it when the next value depends on the current one, such as incrementing. React supplies the latest queued value.

3. Why should state objects and arrays be copied?

A copy creates a new reference. Mutating and reusing the old one can hide the update from React.

4. What does a state snapshot mean?

Each render's event handlers see the state values from that render.

  • A setter schedules a later render.
  • The current variable does not change in place.
5. When should a setter receive a function?

Use a functional updater when the next value depends on the previous value.

  • React supplies the latest queued value to the updater.
  • A direct value works when the replacement is already known.
6. How should an item be changed in a state array?

Use a new array and copy the item being changed.

  • map can replace one matching record.
  • Avoid mutating the original array with push or direct assignment.
7. Why type state initialized with null?

The initial value alone would otherwise limit the state to null.

  • Use a union such as string | null for later values.
  • Handle the null case before reading the selected value.
8. Should derived values usually be stored in state?

No, calculate them during rendering when they can be derived from existing state and props.

  • This avoids keeping duplicate values in sync.
  • Store a value when it represents independent changing state.
9. When might a reducer fit better than several setters?

A reducer can clarify many related state transitions.

  • It collects transition rules in one function.
  • Simple independent values are easier to keep in useState.
10. Does a TypeScript state type check API values?

No. Static types do not inspect runtime JSON.

  • Validate external values before storing them.
  • Keep credentials and private data out of client state and logs.

Further Reading

Conclusion

Treat state as a render snapshot. Choose setters based on whether the next value uses old state, copy objects and arrays, and validate external data before storing it.

Category

Related Posts

Context for Shared State in React

Learn how React context providers pass typed values to consumers, when context helps avoid prop drilling, and when local state or a store fits better.

#react #typescript #context

React Effects with useEffect: Synchronizing Systems

Learn when React effects are needed, how dependencies control resynchronization, and how cleanup prevents leaked timers and subscriptions.

#react #typescript #useeffect

Sharing State and Lifting State Up in React

Learn when sibling React components need shared state, how to lift it to their nearest common owner, and why local state often beats global state.

#react #typescript #state