React / 95
Typing state, events and refs
When TypeScript can work out a hook's type by itself, when you must spell it out, and the event and ref types you'll use every day.
useState: let it infer
const [count, setCount] = useState(0); // number
const [query, setQuery] = useState(""); // string
const [isOpen, setIsOpen] = useState(false); // booleanTypeScript reads the type from the initial value. setCount("five") is now an error. That covers most state. It breaks down when the starting value doesn't show what will go in later:
useState(0)→ number
Good: Inference is enough.
useState("")→ string
Good: Inference is enough.
useState(null)→ null
Problem: Stuck at null forever. You can never store a user.
useState<User | null>(null)→ User | null
Good: Say what it will hold later.
useState([])→ never[]
Problem: An array that can hold nothing.
useState<string[]>([])→ string[]
Good: Name the item type.
State that starts empty
A user you haven't loaded yet starts as null. Tell TypeScript what it will hold later with a type argument in angle brackets:
import { useEffect, useState } from "react";
type User = { id: number; firstName: string };
type Status = "loading" | "done" | "error";
export function Profile() {
const [user, setUser] = useState<User | null>(null);
const [status, setStatus] = useState<Status>("loading");
useEffect(() => {
fetch("https://dummyjson.com/users/1")
.then((res) => res.json())
.then((data: User) => { setUser(data); setStatus("done"); })
.catch(() => setStatus("error"));
}, []);
if (status === "error") return <p>Couldn't load the profile.</p>;
if (!user) return <p>Loading…</p>;
return <h1>Hi, {user.firstName}</h1>; // user is User here, not null
}User | null means "a User or null". After if (!user) return, TypeScript knows user can't be null below, so user.firstName is allowed. A union of strings (Status) is a neat way to say "only these values": setStatus("finished") is an error.
Events
Inline handlers need no types. TypeScript knows onChange on an <input> receives a change event, so e is typed for you:
<input onChange={(e) => setEmail(e.target.value)} />Move the handler into its own function and that context is gone, so name the event type:
import { useRef, useState } from "react";
export function SignupForm() {
const [email, setEmail] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setEmail(e.target.value);
}
function handleSubmit(e: React.SubmitEvent<HTMLFormElement>) {
e.preventDefault();
if (!email.includes("@")) inputRef.current?.focus();
}
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} type="email" value={email} onChange={handleChange} />
<button type="submit">Sign up</button>
</form>
);
}The React. prefix works in type positions without importing React. The pattern is always React.SomethingEvent<TheElement>:
| Handler | Event type |
|---|---|
onChange on <input> | React.ChangeEvent<HTMLInputElement> |
onChange on <select> / <textarea> | React.ChangeEvent<HTMLSelectElement> / <HTMLTextAreaElement> |
onSubmit on <form> | React.SubmitEvent<HTMLFormElement> |
onClick | React.MouseEvent<HTMLButtonElement> |
onKeyDown | React.KeyboardEvent<HTMLInputElement> |
onFocus / onBlur | React.FocusEvent<HTMLInputElement> |
Not sure which one? Write the handler inline first and hover e in your editor. It tells you the exact type.
Refs
A ref to a DOM element starts as null and React fills it in after the element mounts. So type it with the element and start it at null:
const inputRef = useRef<HTMLInputElement>(null);
// inputRef.current is HTMLInputElement | null
inputRef.current?.focus(); // ?. skips the call while it's nullA ref that holds your own value, such as a timer id, works the same way:
const timerId = useRef<number | null>(null);
timerId.current = window.setInterval(tick, 1000);In React 19, useRef always needs an argument. useRef<HTMLInputElement>() fails with Expected 1 arguments, but got 0.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
