Hooks
59 bites tagged Hooks — interview questions with model answers, and 60-second explainers.
How do you use useState to track user input?
Initialize with useState at top level, bind input value to state, and update via onChange using setter. Whether you know useState basics for controlled inputs. Calling useState conditionally or mutating state directly.
Rules of Hooks: Call Order Is Sacred
Hook calls must keep the same order every render because React maps them to state by array index. Only call hooks at the top level of React functions. Break the order and React desyncs, producing stale state or crashes.
Describe using a pre-push Git hook for checks and its CI limitations.
It tests client-side automation versus server-side policy. An executable .git/hooks/pre-push script runs tests and exits non-zero to block, noting hooks are not cloned, skipped via --no-verify, and local-only. A red flag is treating them as policy gate.
SvelteKit Hooks: Intercepting Requests and Events
SvelteKit Hooks are like middleware, letting you intercept requests and events to run app-wide logic. Use them for tasks like authentication checks, initializing DB clients, or custom routing.
The useSearchParams Hook for URL Queries
The useSearchParams hook gives your client component read-only access to the URL's query string. Use it to build UIs that react to URL changes, like filtering a list or displaying search results.
useNavigate: Programmatic Navigation in React
The `useNavigate` hook gives you a function to change routes from your component's logic, like after a form submission. Use it for event-driven navigation, such as sending a user to their dashboard after login.
useParams: Accessing Dynamic URL Segments
The `useParams` hook lets client components read dynamic URL segments. On a route like `/posts/[slug]`, it returns an object like `{ slug: 'my-post' }`. Remember, it's for client components only and won't see query strings.
React State Updates: The Queue and the Updater Function
React batches state updates from one event, like a waiter taking a full order before heading to the kitchen. This prevents multiple re-renders. The footgun: `setCount(count + 1)` called three times only increments once, as `count` is fixed for that render.
React Refs: An Escape Hatch for DOM Manipulation
A ref is an escape hatch to directly access a DOM node, bypassing React's declarative state flow. Use it for imperative actions like focusing an input or scrolling to an element. The footgun: overusing refs can conflict with React's rendering.
React's useFormStatus: Read Form State from a Child Component
The `useFormStatus` hook lets a child component read its parent form's submission status without prop drilling. Use it to disable a submit button or show a loading spinner from within a reusable component.
useFormState (now useActionState): State for Actions
useActionState (formerly useFormState) lets you update state from an async Action. It returns the action's result, a dispatch function, and a pending status. Use it to manage form UI for loading states and validation messages from Server Actions.
Debouncing vs. Throttling in React
Debouncing waits for a pause in events before acting; throttling fires at a steady rate. Use debounce for search bars to avoid API calls on every keystroke, and throttle for scroll handlers to prevent lag.
useRouter: Programmatic Navigation in Next.js
The useRouter hook gives you a router object to programmatically control navigation. Use it for event-driven redirects, like sending a user to their dashboard after a successful login.
useDebugValue: Label Your Custom Hooks in DevTools
useDebugValue attaches a readable label to your custom hooks in React DevTools. Instead of just seeing raw state, you can display a meaningful string like "Online". The footgun is overusing it; reserve it for complex, shared library hooks.
useSyncExternalStore: Safely Read from External State
useSyncExternalStore lets your React components safely subscribe to data outside of React's state. Use it to connect to state libraries like Zustand or browser APIs. The main footgun: your `getSnapshot` function must return an immutable, cached value.
useDeferredValue: Keep UI Responsive During Renders
useDeferredValue keeps your UI responsive by showing a stale value while a new, expensive-to-render value is prepared in the background. Use it for search inputs filtering large lists.
useTransition: Keep Your UI Responsive During State Changes
useTransition lets you update state without blocking the UI, keeping your app responsive. Use it for slow renders like filtering large lists, while the `isPending` flag shows a loading state.
useImperativeHandle: Expose a Custom Ref API
useImperativeHandle exposes a custom API via a ref, letting a parent call specific methods on a child. Instead of exposing an entire DOM node, you can provide a handle with methods like `reset()` or `focus()`.
useLayoutEffect: Synchronous Effects Before Browser Paint
useLayoutEffect is useEffect's synchronous twin, running its code after DOM mutations but before the browser repaints. Use it to read DOM layout and re-render to prevent visual flickers, like positioning a tooltip. Its main footgun: it blocks rendering.
React's Stale Closure Problem in Hooks
A `useEffect` closure captures props and state from its render. If the effect doesn't re-run, its functions can operate on old, "stale" data. This surfaces in timers or socket listeners. The footgun is omitting dependencies, which causes these subtle bugs.
useMemo: Cache Expensive Calculations in React
The useMemo hook caches a function's return value, preventing slow calculations from running on every render. Use it to skip heavy data filtering unless its inputs change. The main footgun is a missing dependency, which leads to stale, cached data.
React's useCallback: Cache Functions, Not Just Values
useCallback gives you the same function instance across re-renders, as long as its dependencies are stable. This is key for optimizing child components with React.memo or preventing useEffect from re-running.
The useReducer Hook: Predictable State Updates
useReducer is a state machine for your components, managing complex state changes predictably. Use it when state logic is complex or the next state depends on the previous one, like in a shopping cart.
Custom Hooks: Package Component Logic for Reuse
A custom hook packages stateful logic (like useState and useEffect) into a reusable function. Use one when multiple components need the same logic, like tracking online status for a status bar and a save button. Footgun: Names must start with `use`.
Get Hooks bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.