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
useState:const [user, setUser] = useState<User | null>(null);useRef:const inputRef = useRef<HTMLInputElement>(null);useReducer: pass a state type and action union to the reducer function.useEffectcallbacks generally do not need types; dependency arrays should be linted witheslint-plugin-react-hooks.- Custom hooks should declare explicit return types for public APIs.
Tips
- Use
useCallbackanduseMemowith typed dependencies to prevent unnecessary re-renders. - When
useRefholds mutable values instead of DOM nodes, useuseRef<T>(initial)without the element constraint.
Common issues
useStatewithout a generic infers the type from the initial value, which may be narrower than intended.useEffectreturning a non-function causes a runtime error that TypeScript can catch if typed correctly.