ProgramGuru

Typing React Events and Hooks

Typing React Events and Hooks — purpose and prerequisites

React event handlers receive typed synthetic events, and hooks expose typed state, refs, and effects. For an input change, event.currentTarget.value is a string; parse it if the application needs a number. Effects should clean up subscriptions and timers that they create.

What you’ll learn

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

How the idea works

An input's value is text, even if type="number". The parser accepts a nonnegative integer and rejects invalid input before a typed handler stores the result in state.

Casting an event value as number changes types only; it does not convert the string from an input element.

Visualize the flow

Typing React Events and Hooks — learning flowChange event → Typed handler + conversion → State updateTyping React Events and Hooks1Change event2Typed handler + conversion3State updateStatic 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

function parseQuantity(text: string): number | null {
  const value = Number(text);
  return Number.isInteger(value) && value >= 0 ? value : null;
}
console.log(parseQuantity("12"));
console.log(parseQuantity("twelve"));

Verified output

12
null

Compile: npx tsc --strict --target es2022 --module commonjs typing-react-events-hooks.ts; run: node typing-react-events-hooks.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

An input's value is text, even if type="number". The parser accepts a nonnegative integer and rejects invalid input before a typed handler stores the result in state.

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

Casting an event value as number changes types only; it does not convert the string from an input element.

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 real TSX example, write onChange={(event) => setText(event.currentTarget.value)} with useState<string>.

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 events and hooks in the example?
Choose one answer. You can try again.

Answer and explanation

An input's value is text, even if type="number".

An input's value is text, even if type="number". The parser accepts a nonnegative integer and rejects invalid input before a typed handler stores the result in state.

Additional official reference

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

Key idea to remember

An input's value is text, even if type="number". The parser accepts a nonnegative integer and rejects invalid input before a typed handler stores the result in state.

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: Forms and Validation in React →