React + TypeScript in practice
Using TypeScript with React means letting inference do most of the work and writing explicit types only at the boundaries: null state, refs, separate event handlers, context and reusable generic components.
42.1 Why is it used?
- Catches bugs like wrong property names or typos before the code runs (npx tsc / the editor).
- Gives autocomplete for props, state, event.target and context values.
- Makes reusable components (List, Table, Select) safe for any kind of data.
- Strict types at the boundaries keep the rest of the app correct by inference.
42.2 The problem: state that starts as null
- TypeScript infers a state type from the initial value: useState(0) is number.
- useState(null) is inferred as only null, so setUser(priya) fails.
React (TSX)
import { useState } from "react";const priya = { name: "Priya" }; export default function Profile() { const [count, setCount] = useState(0); const [user, setUser] = useState(null); const login = () => setUser(priya); return ( <button onClick={login}>Login</button> );}Output
$ npx tscProfile.tsx:7:31 - error TS2345:Argument of type '{ name: string; }'is not assignable to parameterof type 'SetStateAction<null>'.- Step 1
1.useState(0) -> number
- Step 2
2.useState("") -> string
- Step 3
3.useState(null) -> only null
- Step 4
4.useState([]) -> never[]
- Step 5
5.null / empty array: give a generic, e.g. useState<User | null>(null)
Inference reads the initial value only
42.3 Fix: give useState a generic
- Create a User type and pass useState<User | null>(null): this is a generic argument.
- Now setUser accepts a User object and null.
- Because user can be null, check it before reading user.name.
React (TSX)
import { useState } from "react";type User = { name: string }; export default function Profile() { const [user, setUser] = useState<User | null>(null); const login = () => setUser({ name: "Priya" }); return ( <button onClick={login}> {user ? `Hi, ${user.name}` : "Login"} </button> );}Output
-- initial --[button] Login -- after click --[button] Hi, Priya42.4 Typing refs
- useRef<HTMLInputElement>(null): the element type plus null, because the input is not on screen until the first render.
- current is HTMLInputElement | null, so use optional chaining: inputRef.current?.focus().
- Clicking Focus puts the cursor in the input.
React (TSX)
import { useRef } from "react"; export default function FocusInput() { const inputRef = useRef<HTMLInputElement>(null); const focus = () => inputRef.current?.focus(); return ( <> <input ref={inputRef} /> <button onClick={focus}>Focus</button> </> );}42.5 Typing events
- Inline handlers in JSX get the event type inferred automatically.
- A separate handler function needs a type: ChangeEvent<HTMLInputElement>, then e.target.value is a string.
- FormEvent for form submit, MouseEvent for clicks.
React (TSX)
import { useState } from "react";import type { ChangeEvent } from "react"; export default function SearchBox() { const [query, setQuery] = useState(""); const onChange = ( e: ChangeEvent<HTMLInputElement> ) => setQuery(e.target.value); return ( <> <input onChange={onChange} /> <p>Searching: {query}</p> </> );}Output
-- initial --Searching: -- after typing "phone" --Searching: phone| Case | Type | Note |
|---|---|---|
| onChange (input, select, textarea) | ChangeEvent<HTMLInputElement> | e.target.value is a string |
| onSubmit (form) | FormEvent<HTMLFormElement> | call e.preventDefault() |
| onClick (button, div) | MouseEvent<HTMLButtonElement> | e.clientX, e.currentTarget |
| useRef to a DOM node | useRef<HTMLInputElement>(null) | ref.current?.focus() |
| Context | createContext<Auth | null>(null) | read through a guard hook |
- Step 1
1.Initial value or inline handler? Let inference work
- Step 2
2.Initial value null or []? Give a generic
- Step 3
3.Separate handler? Use React types (ChangeEvent, FormEvent)
- Step 4
4.DOM ref? useRef<Element>(null)
- Step 5
5.Context? createContext<T | null>(null) + guard hook
42.6 Typed context and a guard hook
- Auth type: user is a string, logout is () => void.
- createContext<Auth | null>(null): outside a provider there is no logged in user.
- useAuth reads the context and throws "No provider" if it is missing, otherwise returns Auth with user and logout guaranteed.
- The null check lives in one place instead of every component.
React (TSX)
import { createContext, useContext } from "react"; type Auth = { user: string; logout: () => void;}; export const AuthContext = createContext<Auth | null>(null); export function useAuth() { const auth = useContext(AuthContext); if (!auth) throw new Error("No provider"); return auth;}Output
Error: No provider42.7 Generic component: List<T>
- Props<T>: items is T[] and render takes one T and returns ReactNode.
- List<T extends Row> means every item must have an id, used as the key.
- At the call site T is inferred from items, so p.name and p.price autocomplete; you never write T by hand.
React (TSX)
import type { ReactNode } from "react";type Row = { id: number };type Props<T> = { items: T[]; render: (item: T) => ReactNode;};export function List<T extends Row>(p: Props<T>) { return ( <ul> {p.items.map((item) => ( <li key={item.id}>{p.render(item)}</li> ))} </ul> );}React (TSX)
import { List } from "./List"; const products = [ { id: 1, name: "Shirt", price: 499 }, { id: 2, name: "Shoes", price: 1999 },]; export default function App() { return ( <List items={products} render={(p) => `${p.name} ₹${p.price}`} /> );}Output
Shirt ₹499Shoes ₹199942.8 Checkpoint: p.title
- Products have no title field. Writing p.title in render fails at compile time, before the code even runs.
- It works because T got the exact product type.
React (TSX)
import { List } from "./List"; const products = [ { id: 1, name: "Shirt", price: 499 }, { id: 2, name: "Shoes", price: 1999 },]; export default function App() { return ( <List items={products} render={(p) => p.title} /> );}Output
$ npx tscApp.tsx:12:24 - error TS2339:Property 'title' does not exist on type'{ id: number; name: string;price: number; }'.42.9 Common mistakes
- Typing the event as any: a typo like e.target.valu gives no error and becomes undefined at runtime.
- With ChangeEvent the editor flags the typo immediately ("Did you mean value?").
- Myth: you must type every variable. Inference does most of the work; types go only at the boundaries.
- React.FC is not needed; a normal function with typed props is the recommended way.
React (TSX)
const onChange = (e: any) => setQuery(e.target.valu);React (TSX)
const onChange = ( e: ChangeEvent<HTMLInputElement>) => setQuery(e.target.valu);42.10 Best practices
- No any; use unknown when you do not know the type.
- A guard hook (like useAuth) for every context.
- Make reusable components (List, Table, Select) generic.
- Keep strict mode on in tsconfig.
42.11 Interview tips
- Most types come from inference; explicit types go only at the boundaries.
- State that starts as null or [] gets a generic: useState<User | null>(null).
- DOM refs: useRef<HTMLInputElement>(null); separate handlers: ChangeEvent, FormEvent, MouseEvent.
- Typed context with a null default plus a guard hook that throws outside the provider.
- Generic components like List<T extends Row> keep autocomplete and errors exact for any data.