Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 132 ยท TypeScript with React

Typing State, Refs, Context and Reducers

Type React hooks correctly. Learn useState with unions and null, useRef for DOM nodes and values, createContext defaults, discriminated-union reducers and custom hook return types.

Props are only half of a React program. The other half is what lives inside components: state, refs, context, reducers and your own hooks. These are where TypeScript pays off most, because state changes over time and mistakes there (a value that is null when you expected an object, an action nobody handles) are the hardest to spot by eye.

Most hook types are inferred from the arguments you pass. The skill is knowing the handful of places where inference is not enough and you must help it: an empty array, a value that starts as null, a context with no sensible default, an action union. This lesson walks through each hook in turn. It builds on TypeScript and React and prepares Generic Components and Advanced Types.

The editor on this site runs JavaScript only, so every TypeScript block here is read-only (tsx). The live examples run the JavaScript equivalent so you can see the behaviour the types describe: the impossible states they forbid, the null they warn about, and the error they turn into a compile error.

useState

When the initial value shows the type, you write nothing:

TSX
const [count, setCount] = useState(0);        // number
const [name, setName] = useState('');          // string
const [done, setDone] = useState(false);       // boolean

TypeScript infers number from 0, and now setCount('five') is an error. You need to add a type argument in three situations.

1. The state starts empty or null. [] alone would be inferred as never[] (an array that can hold nothing useful), and null alone as just null.

TSX
type User = { id: number; name: string };

const [items, setItems] = useState<string[]>([]);
const [user, setUser] = useState<User | null>(null);

With User | null the compiler forces you to deal with the missing case before you touch the data:

TSX
return <p>{user.name}</p>;            // error TS18047: 'user' is possibly 'null'.
return <p>{user ? user.name : 'Guest'}</p>;   // fine
return <p>{user?.name ?? 'Guest'}</p>;        // also fine

2. The state is a union of string literals. Without help, TypeScript widens 'idle' to string:

TSX
type Status = 'idle' | 'loading' | 'done';
const [status, setStatus] = useState<Status>('idle');
setStatus('finished');   // error TS2345: Argument of type '"finished"' is not assignable to parameter of type 'SetStateAction<Status>'.

3. The initial value is computed lazily and returns a wider type: useState<Settings>(() => readSettings()).

The setter is typed for you. It accepts a new value or an updater function, setCount((previous) => previous + 1), where previous has the state's type. Prefer the updater whenever the new value depends on the old one.

Make impossible states impossible

A very common design is several booleans: isLoading, isError, plus data. Four booleans allow sixteen combinations, and most of them are nonsense ("loading and failed at the same time"). A union of states allows only the meaningful ones, and TypeScript makes each state carry exactly the data that belongs to it.

TSX
type FetchState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; users: User[] }
  | { status: 'error'; message: string };

const [state, setState] = useState<FetchState>({ status: 'idle' });

if (state.status === 'success') {
  // here TypeScript knows state.users exists
  return <p>{state.users.length} users</p>;
}
if (state.status === 'error') {
  return <p role="alert">{state.message}</p>;
}

Inside each if, the compiler narrows the union, so state.users is available only for success, and reading state.message anywhere else is an error. Try the two designs side by side. Press "Start" and then "Fail" in each:

Boolean flags versus a state union

After "Start" then "Fail", the boolean version shows isLoading = true, isError = true and the red warning, because setting one flag does not clear the other. The union version shows {"status":"error","message":"Network down"}: setting a new state replaces the old one, so "loading" disappears automatically. In TypeScript the union version also cannot even express the contradiction. This is the single most useful modelling trick for state; see Choosing State Structure.

useRef

useRef has two jobs, and they are typed slightly differently.

A reference to a DOM element. Give the element type and start with null, because React fills the ref in after the first render:

TSX
import { useEffect, useRef } from 'react';

function SearchField() {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();      // current is HTMLInputElement | null
  }, []);

  return <input ref={inputRef} />;
}

inputRef.current is typed HTMLInputElement | null, which honestly reflects the first render: nothing is attached yet. The ?. handles it. Do not silence this with inputRef.current!, unless you are inside code that can only run after mount (an event handler or effect) and you have thought about it. The name of the element type matters: HTMLInputElement, HTMLButtonElement, HTMLDivElement, HTMLFormElement, HTMLCanvasElement, and so on.

A mutable box that does not trigger renders. Here the ref holds a value of your choosing, such as a timer id or the previous value:

TSX
const timerId = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const clicks = useRef(0);        // inferred as { current: number }

function schedule() {
  clearTimeout(timerId.current);
  timerId.current = setTimeout(() => console.log('fired'), 300);
}

In React 19's types useRef always requires an initial argument (hence undefined above). See what the typing says about null in practice:

A ref is null until React fills it

The first log line is render 1: inputRef.current is null: during the first render the input does not exist yet. Then the effect runs and prints effect: inputRef.current is INPUT. Press "Count a click" twice and the log reads clicks.current = 1 and clicks.current = 2, but the paragraph still says 0, because changing a ref does not re-render. Press "Re-render" and it updates to 2. This is exactly why the DOM ref is typed | null and the value ref is not. More in useRef.

In React 19, ref is an ordinary prop, so a component that wants to expose its input just declares it:

TSX
import type { Ref } from 'react';

type TextFieldProps = { label: string; ref?: Ref<HTMLInputElement> };

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

No forwardRef is needed. The parent passes ref={inputRef} with a useRef<HTMLInputElement>(null).

useEffect, useMemo and useCallback

These mostly infer their types. Two rules matter:

  • An effect callback must return nothing or a cleanup function. An async function returns a promise, so this is an error: useEffect(async () => { ... }, []) gives Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'. Define an async function inside and call it, as in Data Fetching.
  • useMemo and useCallback take their type from what you return; annotate parameters of callbacks since nothing else tells TypeScript what they are: useCallback((id: number) => remove(id), [remove]).

Context

createContext needs a default value, and the default decides the type. There are two approaches.

1. A real default. Good when the context is optional and has a sensible fallback:

TSX
type Theme = 'light' | 'dark';
const ThemeContext = createContext<Theme>('light');

2. null plus a guard hook. Good when a provider is required, which is the usual case for anything stateful. The context type includes null, and a custom hook checks it once so that consumers never see null:

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

type Theme = 'light' | 'dark';

type ThemeContextValue = {
  theme: Theme;
  toggleTheme: () => void;
};

const ThemeContext = createContext<ThemeContextValue | null>(null);

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light');
  const value: ThemeContextValue = {
    theme,
    toggleTheme: () => setTheme((current) => (current === 'light' ? 'dark' : 'light')),
  };
  return <ThemeContext value={value}>{children}</ThemeContext>;
}

export function useTheme(): ThemeContextValue {
  const context = useContext(ThemeContext);
  if (context === null) {
    throw new Error('useTheme must be used inside <ThemeProvider>');
  }
  return context;
}

After the if, TypeScript has narrowed context from ThemeContextValue | null to ThemeContextValue, so callers write const { theme, toggleTheme } = useTheme(); with no null checks. Keep the context object itself unexported, and export only the provider and the hook; then it is impossible to use the context incorrectly. In React 19 you can render <ThemeContext value={...}> directly, without .Provider. The runtime version:

A context with a guard hook

Now the mistake the guard exists for: using the hook outside the provider. With a default of null and no guard, the failure would be a confusing Cannot destructure property 'theme' of ... as it is null somewhere far away. With the guard, the message names the actual problem. More patterns in Context and Context Patterns.

Using the hook without its provider (fails on purpose)

The page stays empty, and the console shows Error: useTheme must be used inside <ThemeProvider>. A one-line guard turned a mystery into a clear instruction.

Reducers and discriminated-union actions

A reducer is a function (state, action) => newState. TypeScript shines here because the action is a discriminated union: every action has a type field (the discriminant), and the other fields depend on it.

TSX
import { useReducer } from 'react';

type CartState = {
  lines: Record<number, number>;   // product id -> quantity
};

type CartAction =
  | { type: 'added'; id: number }
  | { type: 'removed'; id: number }
  | { type: 'quantitySet'; id: number; quantity: number }
  | { type: 'cleared' };

function cartReducer(state: CartState, action: CartAction): CartState {
  switch (action.type) {
    case 'added':
      return { lines: { ...state.lines, [action.id]: (state.lines[action.id] ?? 0) + 1 } };
    case 'removed': {
      const { [action.id]: _removed, ...rest } = state.lines;
      return { lines: rest };
    }
    case 'quantitySet':
      return { lines: { ...state.lines, [action.id]: action.quantity } };
    case 'cleared':
      return { lines: {} };
    default: {
      const unreachable: never = action;
      throw new Error('Unhandled action: ' + JSON.stringify(unreachable));
    }
  }
}

function Cart() {
  const [state, dispatch] = useReducer(cartReducer, { lines: {} });
  dispatch({ type: 'added', id: 7 });           // fine
  dispatch({ type: 'quantitySet', id: 7 });     // error: Property 'quantity' is missing
  dispatch({ type: 'add', id: 7 });             // error: '"add"' is not assignable to the action types
  return null;
}

Three things to notice:

  1. Narrowing in the switch. In case 'quantitySet', action.quantity exists; in case 'cleared' there are no other fields. Typos in type are errors.
  2. dispatch is typed for you from the reducer. Its type is Dispatch<CartAction>; use that name when you pass dispatch as a prop.
  3. The never trick. In default, every case has been handled, so action has type never. Assigning it to a never variable compiles only when that is true. If someone adds { type: 'discounted'; code: string } to the union and forgets the case, the assignment becomes an error, pointing exactly at the reducer that needs updating.

Remember that types disappear at runtime, so the default branch should still throw: it protects you from an action you did not know about, for example one coming from untyped code. Here is the runtime picture:

A reducer with an exhaustive default

The console shows the reducer working without any component: added 7 -> {"lines":{"7":1}}, added 7 -> {"lines":{"7":2}}, and so on, ending with caught: Unhandled action: {"type":"add","id":7}. That 'add' is the typo TypeScript would have flagged at the call site. In the live widget, the buttons build the object {"7":1,"9":1} and so on. More in Reducers.

Custom hook return types

A custom hook is a function, and you type its parameters and return value like any other. Two shapes are common:

TSX
import { useCallback, useState } from 'react';

// A tuple, like useState: the caller names the parts.
function useToggle(initial = false): [boolean, () => void] {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn((current) => !current), []);
  return [on, toggle];
}

// An object, when there are more than two things or the names matter.
function useCounter(start = 0) {
  const [count, setCount] = useState(start);
  return {
    count,
    increment: () => setCount((c) => c + 1),
    reset: () => setCount(start),
  };
}

For a tuple, write the return type ([boolean, () => void]) or end with return [on, toggle] as const. Without that, TypeScript infers (boolean | (() => void))[], an array that can hold either, and destructuring gives you the useless union for both names. For objects the return type is inferred and the compiler guarantees the names and types. A good rule: tuples for exactly two values where renaming at the call site is natural, objects otherwise.

Tuple hook and object hook

The same hook is used twice under different names (isOpen/toggleOpen and isDark/toggleDark); that is the benefit of a tuple. The counter hook returns an object, so the caller picks only what it needs. Hook design is covered in Custom Hooks.

A short checklist

  • Let inference work; add useState<T> for null, empty arrays and literal unions.
  • Model state as a union of states instead of booleans.
  • useRef<HTMLElement>(null) for DOM nodes (the value is | null); useRef<T>(initial) for values.
  • Context: put | null in the type and expose a hook that throws, so consumers get a clean type.
  • Reducer actions are a discriminated union; end the switch with a never check.
  • Hooks that return two values may return a tuple (with an explicit type); otherwise return an object.
  • Avoid any and as as shortcuts; if you need them, comment why.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does useState([]) cause trouble in TypeScript, and what is the fix?

    An empty array literal gives TypeScript no information about the element type. Supply a type argument such as useState<string[]>([]).
  2. 2. In the boolean-flags demo, what happened after pressing Start then Fail?

    Each setter changes only its own flag. A union of states replaces the whole state, so contradictions cannot occur.
  3. 3. Why is useRef<HTMLInputElement>(null).current typed HTMLInputElement | null?

    The demo logged null during the first render and INPUT in the effect. The type reflects that honest timeline.
  4. 4. What is the purpose of the never assignment in a reducer's default branch?

    When all cases are handled, action has type never. If a case is missing, the assignment fails to compile, pointing at the reducer.
  5. 5. A hook returns [on, toggle] without any annotation. What does TypeScript infer, and how do you fix it?

    Array literals are inferred as arrays, not tuples. Annotate the return type or use as const so each position keeps its own type.

Summary

  • useState infers its type; add a type argument for null, empty arrays and literal unions, and use a union of states instead of several booleans.
  • DOM refs are useRef<Element>(null) with a | null value; value refs hold anything and do not cause re-renders.
  • Effect callbacks cannot be async; give callback parameters their types.
  • For required providers, create the context as Value | null and expose a hook that throws, so consumers get a non-null type and a clear error.
  • Type reducer actions as a discriminated union and finish with a never check; dispatch is typed automatically.
  • Return tuples (with an explicit type or as const) or objects from custom hooks.

Next: Generic Components and Advanced Types