ProgramGuru

Typing React Props and State

Typing React Props and State — purpose and prerequisites

React props represent inputs; state represents values that can change over time through React's state APIs. Use explicit prop types and infer state when the initial value is unambiguous. Never mutate a React state array and expect React to notice; use the setter to replace it with an updated value.

What you’ll learn

  • Explain the purpose of typing react props and state.
  • Identify the typed contract, runtime responsibilities and common pitfalls.
  • Run the example and extend its behavior with a practical exercise.

How the idea works

The old array remains length one; the new array has two elements. A React state setter can receive the new array, enabling a predictable UI update.

Pushing into an existing state array mutates it and can make updates hard to track; use immutable replacement and a stable key.

Visualize the flow

Typing React Props and State — learning flowTyped props → State updater → New UI renderTyping React Props and State1Typed props2State updater3New UI renderStatic contracts need runtime checks at external boundaries.
A three-step view of the responsibilities and the observable result.

Run the checked TypeScript example

This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.

TypeScript source

type Todo = Readonly<{ id: number; title: string }>;
function appendTodo(items: readonly Todo[], todo: Todo): Todo[] {
  return [...items, todo];
}
const before: Todo[] = [{ id: 1, title: "Read" }];
const after = appendTodo(before, { id: 2, title: "Write" });
console.log(before.length, after.length);

Verified output

1 2

Compile: npx tsc --strict --target es2022 --module commonjs typing-react-props-state.ts; run: node typing-react-props-state.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.

Trace the execution

The old array remains length one; the new array has two elements. A React state setter can receive the new array, enabling a predictable UI update.

Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.

Build the practical integration

Integration companion: The primary example above is self-contained. The files below demonstrate a real framework, runtime, or project setup and may need additional packages or a browser.

src/Tasks.tsx

import { useState, type FormEvent } from "react";
type Todo = Readonly<{ id: number; title: string; done: boolean }>;
export default function Tasks() {
  const [tasks, setTasks] = useState<Todo[]>([]);
  const [title, setTitle] = useState("");
  function add(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!title.trim()) return;
    setTasks(current => [...current, { id: Date.now(), title: title.trim(), done: false }]);
    setTitle("");
  }
  return <section><h1>Tasks</h1><form onSubmit={add}>
    <input aria-label="Task title" value={title} onChange={e => setTitle(e.currentTarget.value)} />
    <button>Add</button></form>
    <ul>{tasks.map(task => <li key={task.id}><label>
      <input type="checkbox" checked={task.done} onChange={() => setTasks(current =>
        current.map(item => item.id === task.id ? { ...item, done: !item.done } : item))} />
      {task.title}</label></li>)}</ul>
  </section>;
}

Setup and execution

npm create vite@latest typed-tasks -- --template react-ts
cd typed-tasks
Edit src/App.tsx with the component shown above
npm install
npm run dev
npm run build

This is a real React TSX component, not a Node-only simulation. Use the React+TypeScript Vite template, and place the component in the application's src/App.tsx. Its imports require React packages and @types/react; browser behavior was not executed in this environment.

Validation: This companion requires the named external packages or browser environment. Its runtime behavior was not executed during the course build.

Common mistake and correction

Pushing into an existing state array mutates it and can make updates hard to track; use immutable replacement and a stable key.

Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.

Your turn: extend the example

In a React component, use useState<Todo[]>([]) and setTodos(previous => appendTodo(previous, next)).

Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.

Check your understanding

Which statement correctly describes typing react props and state in the example?
Choose one answer. You can try again.

Answer and explanation

The old array remains length one; the new array has two elements.

The old array remains length one; the new array has two elements. A React state setter can receive the new array, enabling a predictable UI update.

Additional official reference

Review the official documentation for the provider, framework or runtime, especially when installing a newer major version.

Key idea to remember

The old array remains length one; the new array has two elements. A React state setter can receive the new array, enabling a predictable UI update.

Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Typing React Events and Hooks →