0Pricing
TypeScript Academy · Lesson

Custom hooks with generics & inference

Write reusable custom hooks with for values, results, and errors; leverage inference and constraints for safe APIs.

Custom hooks with generics & inference is a free TypeScript Academy lesson on CoddyKit — lesson 1 of 2. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 2 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Intro

Goal: Build generic hooks that feel native: a typed localStorage hook, an async loader, and a controlled/uncontrolled helper. You will rely on inference so callers rarely annotate types.

  • Return tuples for React-like ergonomics
  • Use constraints when needed
  • Keep no any

useLocalStorage<T>

Return a [value, set] tuple like useState. Keep T consistent across value and setter.

import { useEffect, useState } from "react"

export function useLocalStorage<T>(key: string, initial: T): [T, (v: T | ((prev: T) => T)) => void] {
  const [value, setValue] = useState<T>(() => {
    try {
      const raw = localStorage.getItem(key)
      return raw ? (JSON.parse(raw) as T) : initial
    } catch {
      return initial
    }
  })

  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(value)) } catch {}
  }, [key, value])

  const set = (v: T | ((prev: T) => T)) => {
    setValue(prev => (typeof v === "function" ? (v as (p: T) => T)(prev) : v))
  }

  return [value, set]
}

// Usage
// const [user, setUser] = useLocalStorage("user", { id: 1, name: "Ada" })

useAsync<T>

Return an object with value, error, loading. The type of value is inferred from the promise returned by fn.

import { useEffect, useState } from "react"

export function useAsync<T>(fn: () => Promise<T>, deps: unknown[] = []) {
  const [value, setValue] = useState<T | null>(null)
  const [error, setError] = useState<unknown>(null)
  const [loading, setLoading] = useState<boolean>(false)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fn().then(
      (v) => { if (!cancelled) { setValue(v); setError(null) } },
      (e) => { if (!cancelled) { setError(e); setValue(null) } }
    ).finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, deps)

  return { value, error, loading }
}

// Usage
// const { value, error, loading } = useAsync(() => fetch("/api").then(r => r.json()))

useControlled<T>

Support both controlled and uncontrolled patterns with one helper. The tuple keeps T aligned.

import { useState } from "react"

type ControlledProps<T> = {
  value?: T
  defaultValue: T
  onChange?: (v: T) => void
}

export function useControlled<T>({ value, defaultValue, onChange }: ControlledProps<T>): [T, (v: T) => void] {
  const [inner, setInner] = useState<T>(defaultValue)
  const isControlled = value !== undefined
  const current = isControlled ? (value as T) : inner
  const set = (v: T) => { isControlled ? onChange?.(v) : setInner(v) }
  return [current, set]
}

// Usage
// const [v, setV] = useControlled({ value, defaultValue: "", onChange: setValue })

Inference & constraints

Prefer inference from arguments; add extends constraints only when your hook needs specific fields.

// Inference works from the initial value
const [settings, setSettings] = useLocalStorage("settings", { theme: "dark", pageSize: 20 })
// T = { theme: string; pageSize: number }

// Constrain T when needed
interface WithId { id: string }
function useById<T extends WithId>(items: T[], id: string) {
  return items.find(x => x.id === id) || null
}

// Usage
const user = useById([{ id: "u1", name: "Ada" }], "u1")

Tips

Tips:

  • Return tuples for React feel and consistent typing.
  • Never use any in public hook signatures.
  • Accept updaters (prev) => next for ergonomic state transitions.

Hook typing check

Quick check: Which signature best fits a generic localStorage hook?

Recap

Recap: You built generic hooks that rely on inference, use constraints only when necessary, and expose tuple/object results that feel like native React APIs.

Frequently asked questions

Is the “Custom hooks with generics & inference” lesson free?

Yes — the full text of “Custom hooks with generics & inference” is free to read here on the web, and the TypeScript Academy course includes 2 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Custom hooks with generics & inference”?

Write reusable custom hooks with for values, results, and errors; leverage inference and constraints for safe APIs. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 2, so you can start here or from the beginning and move at your own pace.

How long does the “Custom hooks with generics & inference” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Custom hooks with generics & inference
  2. Suspense & error boundaries types
← Back to TypeScript Academy