Skip to article content
FrontendXLesson 33 / 40

Typing hooks and generic hooks

Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.

intermediate · about 45 minutes · 3 exercises

  • Predict
  • Implement
  • Debug

What you will be able to do

#
  • Type useState, useRef and useReducer.
  • Write a generic custom hook.
  • Type event handlers and callbacks.

Overview

#

useState

snippet.tsx
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);

Without an argument the state type is inferred from the initial value; pass a type argument when the initial value is not representative.

useRef

snippet.tsx
const inputRef = useRef<HTMLInputElement>(null);
const valueRef = useRef<number>(0);

A ref initialized with null and a DOM type is a read-only ref object; a mutable ref holds a current value you can reassign.

useReducer

snippet.tsx
type State = { count: number };
type Action = { type: "inc" } | { type: "add"; amount: number };
function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "inc": return { count: state.count + 1 };
    case "add": return { count: state.count + action.amount };
    default: {
      const exhaustive: never = action;
      return exhaustive;
    }
  }
}

The discriminated action union makes the switch exhaustive; the default branch proves it by assigning the narrowed never, which the declared return type needs to compile.

Generic custom hook

snippet.tsx
function useToggle<T>(initial: T, next: T): [T, () => void] {
  const [value, setValue] = useState(initial);
  return [value, () => setValue(next)];
}

Event handlers

snippet.tsx
function onChange(event: React.ChangeEvent<HTMLInputElement>) {
  console.log(event.target.value);
}

Use the React event type rather than a hand-written shape.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement a generic `useToggle<T>(initial: T, next: T): [T, () => void]`.

    starter.typescript
    import { useState } from "react";
    
    export function useToggle<T>(initial: T, next: T): [T, () => void] {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    import { useState } from "react";
    
    export function useToggle<T>(initial: T, next: T): [T, () => void] {
      const [value, setValue] = useState<T>(initial);
      return [value, () => setValue(next)];
    }
    

    Authored expected output: Compiles with no errors. Runtime: calling the setter switches the value to next.

    The generic T flows from the arguments into the state and the returned tuple.

  2. Exercise 2Predict

    What is the state type here? ```tsx const [items, setItems] = useState([]); ```

    Choose the best answer
  3. Exercise 3Debug

    This fails because the action union is not narrowed. Fix the reducer. ```tsx type Action = { type: "inc" } | { type: "add"; amount: number }; function reducer(state: number, action: Action) { return state + action.amount; } ```

    starter.typescript
    type Action = { type: "inc" } | { type: "add"; amount: number };
    function reducer(state: number, action: Action) { return state + action.amount; }
    

    Reveal the reference answer
    reference.typescript
    type Action = { type: "inc" } | { type: "add"; amount: number };
    function reducer(state: number, action: Action) {
      return action.type === "add" ? state + action.amount : state + 1;
    }
    

    Authored expected output: Compile error resolved: Property 'amount' does not exist on type '{ type: "inc" }'. Narrowing on action.type fixes it.

    The discriminant must be checked before the member is read.

Common misconceptions

#
  • useState infers the narrowest type from the initial value.
  • useRef always returns a nullable ref.
  • A reducer action can be any string.

Follow-up practice

#
  • typescript-api-client

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.