How to type React hooks in TypeScript

· Category: TypeScript

Short answer

TypeScript infers hook types from initial values, but you should provide explicit generics for complex state, refs, and reducers.

Steps

  1. useState: const [user, setUser] = useState<User | null>(null);
  2. useRef: const inputRef = useRef<HTMLInputElement>(null);
  3. useReducer: pass a state type and action union to the reducer function.
  4. useEffect callbacks generally do not need types; dependency arrays should be linted with eslint-plugin-react-hooks.
  5. Custom hooks should declare explicit return types for public APIs.

Tips

  • Use useCallback and useMemo with typed dependencies to prevent unnecessary re-renders.
  • When useRef holds mutable values instead of DOM nodes, use useRef<T>(initial) without the element constraint.

Common issues

  • useState without a generic infers the type from the initial value, which may be narrower than intended.
  • useEffect returning a non-function causes a runtime error that TypeScript can catch if typed correctly.