React Hooks Types in TypeScript
React Hooks Types
Section titled “React Hooks Types”useState
Section titled “useState”const [count, setCount] = useState<number>(0);const [user, setUser] = useState<User | null>(null);
// Type inference works for simple casesconst [name, setName] = useState(""); // inferred as stringuseRef
Section titled “useRef”const inputRef = useRef<HTMLInputElement>(null);const intervalRef = useRef<number | undefined>(undefined);
// Mutable refconst countRef = useRef(0);countRef.current += 1;useReducer
Section titled “useReducer”type Action = | { type: 'increment'; payload?: number } | { type: 'decrement' } | { type: 'reset' };
interface State { count: number }
function reducer(state: State, action: Action): State { switch (action.type) { case 'increment': return { count: state.count + (action.payload ?? 1) }; case 'decrement': return { count: state.count - 1 }; case 'reset': return { count: 0 }; }}Interview Questions
Section titled “Interview Questions”Easy: How do you type useState with a complex object?
Medium: How do you type useReducer with discriminated unions?
Hard: How does useRef differ for DOM refs vs mutable values?