AI Hints
Home›React Tutorial›TypeScript and Patterns
React · Lesson 61 of 120

Typing State and Events

UseState<T>.

⏱ 2 min read▶ Video at 50:37🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

TypeScript usually works out the type of state from its starting value. Sometimes you need to help it. And event handlers have their own types.

  • Types inferred
  • Sometimes help it
  • Event types

A typed form

Use state usually works out the type from the starting value. For empty arrays and unions, pass the type in angle brackets. Event handlers use React's event types, like change event of an input element. We type an email, and submit. Run it.

App.tsxtsx
import { useState, type ChangeEvent, type FormEvent } from "react";
type Status = "idle" | "sent";
export default function App() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<Status>("idle");
  const [errors, setErrors] = useState<string[]>([]);
  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    setEmail(e.target.value);
  }
  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (!email.includes("@")) return setErrors(["Enter a valid email"]);
    setErrors([]);
    setStatus("sent");
  }
  return <form onSubmit={handleSubmit}><input id="e" value={email} onChange={handleChange} /> <button>Join</button>
    <p>Status: {status}</p>{errors.map(e => <small key={e}>{e}</small>)}</form>;
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#e", "text": "leo@example.com"}, {"key": "Enter"}]

Common event types

Typing in an input is a change event. Submitting a form is a form event. Clicking is a mouse event. Each takes the element type in angle brackets.

EventType
onChangeChangeEvent<HTMLInputElement>
onSubmitFormEvent<HTMLFormElement>
onClickMouseEvent<HTMLButtonElement>

Summary

Pass a type to use state when it can't be inferred, and use React's event types in handlers. Next, composition.

Key takeaways
  • useState<Status>
  • ChangeEvent
  • FormEvent
Next up: Composition — components inside components