tsxANYreacthookstypescriptuseState
tsx
const [user, setUser] = useState<User | null>(null);Useful when TypeScript cannot infer the full intended state type from the initializer.
Type-safe React Hooks patterns for state, refs, reducers, and custom hooks.
Typing common hooks in TypeScript.
const [user, setUser] = useState<User | null>(null);Useful when TypeScript cannot infer the full intended state type from the initializer.
const inputRef = useRef<HTMLInputElement | null>(null);Typing refs correctly improves DOM API autocomplete and safety.
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'reset'; payload: number };Discriminated unions give exhaustive reducer switch safety.
Typed custom hook APIs and generics.
function useBoolean(initial = false): readonly [boolean, () => void] {
const [value, setValue] = useState(initial);
const toggle = () => setValue(v => !v);
return [value, toggle] as const;
}`as const` preserves tuple semantics for callers.
type AsyncResult<T> = {
data: T | null;
error: Error | null;
loading: boolean;
};A reusable result type keeps async hook contracts consistent.