Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 96 ยท TypeScript in Practice

TypeScript with React

Learn how to use TypeScript with React - typing props, children, state, events, refs, reducers, context and generic components, with the patterns teams use every day.

React and TypeScript are one of the most popular pairings in front-end development. React components are just functions, and props are just objects, so everything you've learned about object types, unions and generics applies directly. The payoff is huge: your editor knows which props a component accepts, refuses a misspelled prop, and tells you what an event handler receives.

This lesson covers the patterns you'll use daily: props and children, state, events, refs, reducers, context and generic components, plus how to wrap native HTML elements. It assumes you know the basics of React (components, JSX, hooks).

Our editor runs plain TypeScript on Node.js, without React or JSX. React code in this lesson is shown as read-only TSX. The runnable examples use plain functions that return strings in place of JSX, so you can try the typing patterns themselves: props unions, reducers, generic components and hook signatures behave exactly the same way in a real React project.

Setting up

Vite's React template (npm create vite@latest my-app -- --template react-ts) and frameworks like Next.js come with TypeScript configured. The settings that matter for React are:

JSON
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "lib": ["es2024", "dom", "dom.iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "noEmit": true
  }
}
  • Files containing JSX must use the .tsx extension.
  • "jsx": "react-jsx" uses the modern JSX transform, so you don't need import React from 'react' in every file.
  • The types come from @types/react and @types/react-dom, installed by the templates. Keep their major version in line with React itself (19 at the time of writing).

Typing props

A component's props are a single object, so you type them with an interface or a type alias and destructure them in the parameter list:

TSX
interface GreetingProps {
  name: string;
  excited?: boolean; // optional prop
}

export function Greeting({ name, excited = false }: GreetingProps) {
  return <p>Hello, {name}{excited ? '!' : '.'}</p>;
}

<Greeting name="Ada" />;           // OK
<Greeting name="Ada" excited />;   // OK: excited is true
<Greeting />;                      // error: Property 'name' is missing
<Greeting name="Ada" exited />;    // error: Property 'exited' does not exist

Notice there's no return type annotation: TypeScript infers it, and the type is the JSX element type React expects. You'll also see const Greeting: React.FC<GreetingProps> = ... in older code. It still works, but most teams now prefer plain functions, which are simpler and handle generics better.

Props that depend on each other

Some components have props that only make sense together. A button might render as a link (needs href) or as a real button (needs onClick), but never both. A discriminated union expresses that precisely. Here's the pattern with a string-returning stand-in for JSX:

TypeScript Props as a discriminated union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
<button class="md">Save</button>
<a class="sm" href="/docs">Docs</a>
<a class="md" href="https://github.com" target="_blank" rel="noopener">GitHub</a>

Inside each case, props is narrowed, so props.href is only available for links and props.disabled only for buttons. In TSX the calls would read <Action as="link" label="Docs" href="/docs" />, and the checks are identical. Here's what the union rejects:

TypeScript Invalid prop combinations (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Nothing runs; the compiler reports both mistakes:

TEXT
main.ts(9,8): error TS2345: Argument of type '{ as: "link"; label: string; }' is not assignable to parameter of type 'ActionProps'.
  Property 'href' is missing in type '{ as: "link"; label: string; }' but required in type '{ as: "link"; label: string; href: string; }'.
main.ts(10,39): error TS2353: Object literal may only specify known properties, and 'href' does not exist in type '{ as: "button"; label: string; onClick: () => void; }'.

Thanks to the as tag, TypeScript knows which member you meant and gives a precise message: the link is missing href, and buttons have no href.

Children

Components that wrap other content receive it as the children prop. Type it with React.ReactNode, which accepts everything React can render: elements, strings, numbers, arrays, null, undefined and booleans:

TSX
import type { ReactNode } from 'react';

interface CardProps {
  title: string;
  children: ReactNode;
  footer?: ReactNode;
}

export function Card({ title, children, footer }: CardProps) {
  return (
    <section className="card">
      <h2>{title}</h2>
      {children}
      {footer && <footer>{footer}</footer>}
    </section>
  );
}

Use React.ReactElement only when you really need an element (for example to clone it), and a function type like (item: T) => ReactNode for "render props".

State with useState

useState is a generic function. Usually it infers the type from the initial value, and you write nothing:

TSX
const [count, setCount] = useState(0);        // number
const [query, setQuery] = useState('');       // string

// When the initial value doesn't show every possibility, pass the type:
const [user, setUser] = useState<User | null>(null);
const [status, setStatus] = useState<'idle' | 'saving' | 'saved'>('idle');

Without <User | null>, the state would be typed as null forever, and setUser(someUser) would fail. The setter accepts either a new value or an updater function that receives the previous state. Here's a simplified version of the signature, runnable outside React so you can see how the types work:

TypeScript A simplified useState signature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
state is now 5
state is now 6
state is now { name: 'Ada', visits: 1 }
state is now { name: 'Ada', visits: 2 }
number null

The last line shows the initial values, because this toy has no re-rendering. What matters is the types: n and u are inferred from S in the updater functions, and setCount('six') would be a compile error. The as casts are needed because a state could itself be a function type, which React's real implementation handles the same way. (One consequence: to store a function in state, you must wrap it, setHandler(() => myFunction).)

Events

React passes its own synthetic events, typed in @types/react. When you write the handler inline, the type is inferred from the prop. When you define it separately, annotate the parameter with the matching event type and element:

TSX
import type { ChangeEvent, FormEvent, KeyboardEvent } from 'react';

function SearchBox() {
  const [query, setQuery] = useState('');

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setQuery(event.currentTarget.value); // value is string
  }

  function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === 'Escape') setQuery('');
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    console.log('search for', query);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={query} onChange={handleChange} onKeyDown={handleKeyDown} />
      <button onClick={(event) => console.log(event.clientX)}>Go</button>
    </form>
  );
}
  • Common event types: ChangeEvent, FormEvent, MouseEvent, KeyboardEvent, FocusEvent, PointerEvent, DragEvent. Import them from react, not the DOM globals of the same names.
  • The generic parameter is the element the handler is attached to; event.currentTarget gets that type.
  • Not sure of the type? Write the handler inline once and hover over event, or use the handler types: const onChange: React.ChangeEventHandler<HTMLInputElement> = (event) => ....

Refs

useRef serves two purposes, and they're typed differently:

TSX
// 1. A reference to a DOM element: start with null, React fills it in.
const inputRef = useRef<HTMLInputElement>(null); // RefObject<HTMLInputElement | null>

useEffect(() => {
  inputRef.current?.focus(); // current may be null before mount
}, []);

return <input ref={inputRef} />;

// 2. A mutable value that survives re-renders (no re-render on change):
const timerId = useRef<number | undefined>(undefined);
timerId.current = window.setTimeout(tick, 1000);

Since React 19, useRef always needs an argument, and ref is a regular prop on function components, so forwardRef is no longer needed for new code:

TSX
interface TextFieldProps {
  label: string;
  ref?: React.Ref<HTMLInputElement>;
}

function TextField({ label, ref }: TextFieldProps) {
  return <label>{label} <input ref={ref} /></label>;
}

Reducers

For state with several related transitions, useReducer pairs well with a discriminated union of actions. The reducer is a pure function, so you can run it right here:

TypeScript A typed reducer for a shopping cart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
2 x Mug
3 x Tea
total 32.50, coupon SPRING10

Every case sees only the fields of its action (action.quantity exists only in setQuantity), and dispatch({ type: 'setQuantity', id: 'p2' }) would be a compile error because quantity is missing. The never check in default (see any, unknown, never) makes the compiler complain if you add an action type and forget to handle it.

Context

createContext needs a default value. Real values usually come from a provider, so a common pattern is to default to null and wrap useContext in a hook that throws a clear error when the provider is missing:

TSX
import { createContext, useContext, useState, type ReactNode } from 'react';

interface AuthContextValue {
  user: { name: string } | null;
  signIn: (name: string) => void;
  signOut: () => void;
}

const AuthContext = createContext<AuthContextValue | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthContextValue['user']>(null);
  const value: AuthContextValue = {
    user,
    signIn: (name) => setUser({ name }),
    signOut: () => setUser(null),
  };
  return <AuthContext value={value}>{children}</AuthContext>;
}

export function useAuth(): AuthContextValue {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used inside <AuthProvider>');
  }
  return context; // narrowed: AuthContextValue, never null
}

Components call useAuth() and get a non-null value without any ! assertions. (<AuthContext value={...}> is the React 19 shorthand for <AuthContext.Provider>.)

Generic components

A component can be generic, just like a function. A list or table that works with any item type, and still knows the item type inside its callbacks, is the classic example:

TypeScript A generic List component

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
<ul>
  <li key="Earth">1. Earth has 1 moon(s)</li>
  <li key="Mars">2. Mars has 2 moon(s)</li>
</ul>
<p>Nothing here</p>

In TSX you write <List items={planets} getKey={(p) => p.name} renderItem={(p) => <b>{p.name}</b>} />, and T is inferred from items in the same way. Inside a .tsx file, a generic arrow function needs a trailing comma, const List = <T,>(props: ListProps<T>) => ..., so the parser doesn't mistake <T> for a JSX tag. Plain function declarations avoid that quirk.

Wrapping native elements

Design-system components often wrap a native element and pass most props through. React.ComponentProps<'button'> gives you every prop a <button> accepts, including onClick, disabled, aria-* and type, so you can extend it with utility types:

TSX
import type { ComponentProps } from 'react';

type ButtonProps = ComponentProps<'button'> & {
  variant?: 'primary' | 'secondary' | 'danger';
};

export function Button({ variant = 'primary', className, ...rest }: ButtonProps) {
  return <button className={`btn btn-${variant} ${className ?? ''}`} {...rest} />;
}

// Every native prop works and is type-checked:
<Button type="submit" disabled aria-label="Save" onClick={(e) => e.preventDefault()} />;

Use Omit<ComponentProps<'input'>, 'size'> when your own prop clashes with a native one, and ComponentProps<typeof OtherComponent> to reuse another component's props.

Common patterns and pitfalls

  • Don't annotate what React infers. Inline handlers, useState(0), useMemo and return types infer well. Annotate props, state that starts as null or [], and handlers defined separately.
  • useState([]) is never[]. An empty array has no element type to infer from; write useState<Todo[]>([]).
  • Avoid any in props. For "anything renderable" use ReactNode; for data use generics or unknown.
  • Model loading states as unions, { status: 'loading' } | { status: 'error'; error: string } | { status: 'ready'; data: T }, instead of separate isLoading, error and data variables that can contradict each other.
  • Validate fetched data before putting it in state, as shown in typing APIs.

Typing a store: Redux Toolkit and Zustand

useReducer and context cover state that belongs to one part of the tree. When many distant components share state (a cart, the signed-in user, a list of open documents), most teams use a store library. The two most popular, Redux Toolkit and Zustand, are both written in TypeScript, and both are designed so that you write one type and let inference do the rest.

Redux Toolkit

Redux Toolkit's createSlice takes a name, an initial state and a map of case reducers. You annotate the state once and give each reducer's action a PayloadAction<T> type. From that, the library generates action creators with exactly the right parameter types:

TypeScript
// features/todos/todosSlice.ts
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';

interface Todo {
  id: number;
  text: string;
  done: boolean;
}

interface TodosState {
  items: Todo[];
  filter: 'all' | 'open' | 'done';
}

const initialState: TodosState = { items: [], filter: 'all' };

const todosSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    added(state, action: PayloadAction<string>) {
      // Immer lets you "mutate" a draft; the store stays immutable
      state.items.push({ id: Date.now(), text: action.payload, done: false });
    },
    toggled(state, action: PayloadAction<number>) {
      const todo = state.items.find((t) => t.id === action.payload);
      if (todo) todo.done = !todo.done;
    },
  },
});

export const { added, toggled } = todosSlice.actions; // added(text: string), toggled(id: number)
export default todosSlice.reducer;

The store setup derives its two key types from the store itself, so they can never go out of date. Typed hooks are then created once and used everywhere instead of the plain useSelector and useDispatch (.withTypes() arrived in React Redux 9.1):

TypeScript
// app/store.ts
import { configureStore } from '@reduxjs/toolkit';
import { useDispatch, useSelector } from 'react-redux';
import todosReducer from '../features/todos/todosSlice';

export const store = configureStore({ reducer: { todos: todosReducer } });

export type RootState = ReturnType<typeof store.getState>; // { todos: TodosState }
export type AppDispatch = typeof store.dispatch;          // knows about thunks too

export const useAppSelector = useSelector.withTypes<RootState>();
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
TSX
function TodoList() {
  const items = useAppSelector((state) => state.todos.items); // Todo[], no annotation
  const dispatch = useAppDispatch();
  return items.map((todo) => (
    <li key={todo.id} onClick={() => dispatch(toggled(todo.id))}>{todo.text}</li>
  ));
}

How can createSlice know that toggled needs a number? It reads each reducer's type with a mapped type and a conditional type using infer, then builds the action type string with a template literal type. This simplified version does the same, so you can watch the inference work (it copies the state with structuredClone where Redux Toolkit uses Immer):

TypeScript A mini createSlice with inferred action creators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
{ type: 'todos/added', payload: 'Write tests' }
[ { id: 2, text: 'Ship it', done: false } ]
1 todos/cleared

The three // @ts-expect-error lines prove the types: each one is an error, so the directive is satisfied and the program runs. Delete the first one and the run stops with error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. A few details are worth noticing:

  • ActionCreators checks Parameters<R[K]>['length']: a reducer that takes no action, like cleared(state), gets a creator with no parameters.
  • The return type of added('Write tests') is PayloadAction<string, 'todos/added'>: the slice name and key are joined into a literal type, which is how Redux Toolkit's action.type stays precise.
  • RootState comes from ReturnType<typeof store.getState>, exactly as in the real setup above.

Zustand

Zustand takes a lighter approach: one hook holds both the state and the functions that change it. You describe the whole store with one interface and pass it to create:

TypeScript
import { create } from 'zustand';

interface CartState {
  items: Record<string, number>;
  add: (id: string) => void;
  count: () => number;
}

export const useCart = create<CartState>()((set, get) => ({
  items: {},
  add: (id) => set((state) => ({ items: { ...state.items, [id]: (state.items[id] ?? 0) + 1 } })),
  count: () => Object.values(get().items).reduce((sum, n) => sum + n, 0),
}));

// In a component: select only what you need, so it re-renders only when that changes
const count = useCart((state) => state.count());
const add = useCart((state) => state.add);

Note the double call: create<CartState>()(...). TypeScript can't infer some type parameters while you specify others, so Zustand splits them across two calls. The first call fixes T to CartState; the second call's parameters (set, get, and the extra ones that middleware such as persist or devtools adds) are then inferred. Here is a working miniature with the same curried shape, where select stands in for calling the hook with a selector:

TypeScript A mini Zustand store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
items: {} -> {"mug":1}
items: {"mug":1} -> {"mug":2}
items: {"mug":2} -> {"mug":2,"tea":1}
items: {"mug":2,"tea":1} -> {"tea":1}
2
[ 'tea', 'pen' ]

Inside the initializer, set and get are typed from CartState, so set({ itmes: {} }) would be an error, and every action's parameters come from the interface. The last add('pen') isn't logged because the listener had already unsubscribed.

Which one should you pick? Both are type-safe. Redux Toolkit suits large apps that want strict structure, middleware, dev tools and RTK Query for server data; Zustand suits apps that want minimal ceremony. Either way, keep server data (fetched lists, user profiles) out of hand-written store code when you can, and validate it at the boundary as shown in typing APIs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of user in const [user, setUser] = useState(null);?

    The type is inferred from the initial value, which is just null. Write useState<User | null>(null) to allow users later.
  2. 2. Which type should you use for a children prop that can be text, elements or nothing?

    ReactNode covers everything React can render, including strings, numbers, elements, arrays, null and undefined.
  3. 3. A handler is defined separately and attached as <input onChange={handleChange} />. How should you type its parameter?

    React passes synthetic events. ChangeEvent<HTMLInputElement> types currentTarget as an HTMLInputElement, so currentTarget.value is a string.
  4. 4. Why is a discriminated union useful for a Button that renders either a link or a button?

    The tag (as) tells TypeScript which set of props applies, so missing or extra props are compile errors and each branch sees only its own fields.
  5. 5. Inside a .tsx file, why might const Box = <T>(props: BoxProps<T>) => ... fail to parse?

    In TSX, <T> looks like the start of an element. A trailing comma (<T,>) or a constraint (<T extends unknown>) makes it a type parameter list.

Summary

  • Type props with an interface or type alias and destructure them; let TypeScript infer the return type. Use discriminated unions for props that depend on each other.
  • Use ReactNode for children and other renderable props.
  • useState infers from the initial value; pass a type argument when it starts as null or [].
  • Type separate event handlers with React's event types (ChangeEvent<HTMLInputElement>, FormEvent<HTMLFormElement>); inline handlers infer theirs.
  • useRef<HTMLInputElement>(null) for DOM refs; in React 19 ref is a normal prop.
  • Model reducer actions as a discriminated union with a never exhaustiveness check, and wrap nullable context in a custom hook.
  • Generic components work like generic functions; ComponentProps<'button'> extends native elements.

Next: TypeScript with Vue, Angular and Express