After this lesson, you will be able to: Type React: props, hooks, events, context, refs.
TS + React is the modern frontend default. This lesson covers the patterns that come up daily.
Function components are simplest.
import { type ReactNode } from "react";type ButtonProps = {children: ReactNode;variant?: "primary" | "secondary";onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;disabled?: boolean;};export function Button({ children, variant = "primary", onClick, disabled }: ButtonProps) {return (<button onClick={onClick} disabled={disabled} className={variant}>{children}</button>);}// Use ComponentProps for forwardingtype InputProps = React.ComponentProps<"input"> & { label: string };
useState + useReducer + useRef + useContext.
import { useState, useReducer, useRef, useContext, createContext } from "react";// useState, explicit when initial is nullconst [user, setUser] = useState<User | null>(null);const [count, setCount] = useState(0); // inferred// useReducertype Action = { type: "inc" } | { type: "set"; value: number };function reducer(state: number, a: Action): number {switch (a.type) {case "inc": return state + 1;case "set": return a.value;}}const [n, dispatch] = useReducer(reducer, 0);// useRefconst inputRef = useRef<HTMLInputElement>(null);// useContextconst UserContext = createContext<User | null>(null);const user2 = useContext(UserContext); // User | null
Same patterns; type return values explicitly.
function useToggle(initial = false): [boolean, () => void] {const [value, setValue] = useState(initial);const toggle = useCallback(() => setValue((v) => !v), []);return [value, toggle];}function useFetch<T>(url: string): { data: T | null; loading: boolean; error: Error | null } {// ... implementationreturn { data, loading, error };}// Type inferred at call site:const { data } = useFetch<User>("/api/me"); // data: User | null
Using FC<Props> (Function Component). Older pattern; just type the function directly. Forgetting `key` types in lists. Typing event handlers as `any`. Use React.MouseEvent / React.ChangeEvent. useRef<HTMLInputElement>() instead of useRef<HTMLInputElement>(null). null initial is required for DOM refs.
Pick the senior answer.
Sign in and purchase access to unlock this lesson.