React
react
Code Snippets
React useDebounce Hook
Debouncing a fast-changing value (a search input, a window resize, a slider) is one of the first React-specific utilities every project needs. This snippet shows the simplest one-state useDebounce hook, a leading-edge variant for instant first reactions, and a useDebouncedCallback variant that wraps a function instead of a value. Pick the shape that matches what your component actually needs.
React useThrottle Hook
Throttling caps the rate at which a value updates while still letting changes through at a steady cadence. This snippet covers the basic useThrottle that emits at most once per window, a useThrottledCallback variant for wrapping functions, and the leading-plus-trailing edge form that keeps the first and last events without dropping the tail. Use it for scroll handlers, mouse trackers, and any high-frequency stream you need to sample.
React useLocalStorage Hook
Persisting a piece of state to localStorage so it survives a page reload is one of the most-requested custom hooks. This snippet covers the basic JSON-serialised hook, an SSR-safe variant that lazily reads only on the client, and a cross-tab sync version that listens for the storage event. Pick the one that matches whether your app is client-only, server-rendered, or multi-window.
React usePrevious Hook
Tracking the previous value of a prop or piece of state lets you diff renders, animate transitions, and detect specific change patterns. This snippet shows the canonical one-liner usePrevious, a useChanged variant that returns whether the value just changed, and a useHistory hook that keeps the last N values for undo / redo. All three are tiny but easy to get subtly wrong.
React useToggle Hook
Boolean state shows up everywhere: modals, drawers, accordions, password visibility, dark mode. The useToggle hook collapses three lines of `useState` plus a setter into one call. This snippet covers the minimal toggle, a value-aware variant that lets callers pin the state to a specific boolean, and an enum-aware version that cycles through any number of states (light / dark / system).
React useIsMounted Hook
Setting state on an unmounted component throws a warning in development and can mask real bugs in production. The useIsMounted hook gives async callbacks a way to bail out before they touch React state. This snippet covers the basic ref-based hook, a useSafeState wrapper that no-ops after unmount, and a useSafeCallback variant that protects the function itself.
React useInterval Hook (Dan Abramov pattern)
Calling setInterval inside useEffect breaks the moment the callback closes over stale state. Dan Abramov's useInterval pattern stores the latest callback in a ref so the timer always fires the freshest version without resetting. This snippet covers the canonical pattern, a pause-aware variant that accepts a null delay, and a useTimeout sibling for one-shot timers.
React useEventListener Hook
Manually attaching DOM event listeners inside useEffect is repetitive and easy to misuse: forgotten cleanups leak handlers, and stale callbacks see old state. The useEventListener hook centralises the pattern so consumers just declare which event they care about. This snippet covers the basic window listener, a target-aware variant that supports any element ref, and a typed signature that picks the right event payload.
React useClickOutside Hook
Dropdowns, popovers, and modals all need to dismiss when the user clicks outside their wrapper. The useClickOutside hook centralises the listener wiring so feature components stay declarative. This snippet covers the pointerdown-based version, an ignore-list variant for portal triggers, and the keyboard escape sibling that completes the dismissal pattern.
React useMediaQuery Hook
Mirroring CSS media queries inside React components keeps logic about responsive breakpoints, dark-mode preference, and reduced motion in one place. The useMediaQuery hook subscribes to a MediaQueryList so renders stay in sync with the browser. This snippet covers the basic match boolean, an SSR-safe variant with an initial fallback, and a useBreakpoint helper that maps named breakpoints onto Tailwind-style logic.
React useCopyToClipboard Hook
A copy-to-clipboard button needs to do three things: write to the clipboard, surface success or failure to the UI, and reset the success indicator after a short delay. This snippet covers a status-aware hook with a one-shot success flag, a fallback variant for older browsers, and a copy-with-format helper that writes both plain text and rich HTML. Drop it next to any 'Copy code' button.
React useFetch Hook with Cancellation
Building a useFetch from scratch teaches the pieces every data-fetching library has to solve: tracking loading and error state, cancelling in-flight requests when the URL changes, and ignoring stale responses after the component unmounts. This snippet covers the canonical AbortController-based hook, a generation-counter variant that protects against race conditions when AbortController is unavailable, and a mutate refetch helper for manual revalidation.
React useInfiniteScroll Hook
Infinite scroll feels simple until you wire IntersectionObserver, page tracking, and the request lifecycle together. This snippet covers a sentinel-ref hook that fires a load callback when the bottom marker scrolls into view, a paginated variant that tracks the page state for you, and an end-of-feed guard that stops calling the callback once the server says there is no more data.
React Conditional Rendering Patterns
Conditional rendering in React looks easy until the `0`-falsy-render bug ships to production. This snippet covers the three patterns you should reach for in order: a ternary in JSX for either-or branches, the `&&` short-circuit (with the famous `0` gotcha and its fix), and an early-return plus extracted helper component when the branching gets dense. Examples render a small text representation of the output so the teaching is independent of any JSX compiler.
Question Banks
React Hooks Fundamentals Quiz
Six drills on the core React hooks: useState, useEffect, useReducer, useCallback, useMemo, and writing custom hooks. Good for tightening mid-level interview answers.
React Component Communication Quiz
Four quick checks on how React components pass data down via props and notify parents via callbacks, plus when render-props become a better tool than another layer of props.
Controlled vs Uncontrolled Components Quiz
Four checks on the controlled / uncontrolled split for React form inputs, including the file-input edge case and the warning React emits when you flip between defaultValue and value.
React State Management Without Redux Quiz
Four checks on the non-Redux options for sharing React state: local component state, Context, useReducer, and lightweight stores like Zustand or Jotai.
Lifting State and Context API Quiz
Six drills on lifting state to a common ancestor, when to switch to Context, and the useReducer + useContext pattern for a small, self-contained store.
React Error Boundaries and StrictMode Quiz
Four drills on class-component error boundaries and how React.StrictMode surfaces effect bugs by double-invoking lifecycles in development.
React Data Fetching and Effects Quiz
Four drills on fetching data with useEffect, avoiding stale closures, and cleaning up in-flight requests when the component unmounts or the input changes.
React Router and Code Splitting Quiz
Four drills on declarative routing with react-router and using React.lazy plus Suspense to split bundles per route or per heavy component.
React Component Patterns and Composition Quiz
Six drills on the classic React patterns: composition over inheritance, render props, higher-order components, compound components, and slot-style children.
React Performance Optimization Quiz
Five drills on memoization, stable references, PureComponent, and the trade-offs between fixing a real render-cost problem and prematurely wrapping everything in memo.
React Rendering and Reconciliation Quiz
Four drills on React's virtual DOM, the reconciliation diffing algorithm, and why stable list keys matter so much.
React Lifecycle and Class Component Quiz
Four drills on legacy class lifecycle methods that still show up in interviews and codebases: mount/update/unmount, getSnapshotBeforeUpdate, setState batching, and getDerivedStateFromProps.
React Portals, Fragments, and StrictMode Quiz
Three drills on three small but tested React features: portals (with their event bubbling quirk), fragments, and what StrictMode does in development.
React Synthetic Events and Event Pooling Quiz
Three drills on React's SyntheticEvent wrapper, how delegation works, and the difference between the React 16 pooling era and React 17+ behavior.
React Refs and Imperative Handles Quiz
Three drills on using refs to reach into the DOM, forwarding a ref through a wrapper component, and using useImperativeHandle to expose a controlled API.
React SSR and Hydration Quiz
Three drills on the difference between SSR and CSR, what hydration actually does, and how React 18 streaming SSR plus selective hydration change the picture.
React ReactDOMServer: Two Explanations Quiz
Two explanations of `react-dom/server` rendering APIs (string vs streaming) plus companions on streaming SSR with `renderToPipeableStream` and on hydration mismatches.
React Controlled vs Uncontrolled Components: Two Explanations Quiz
Two explanations of controlled vs uncontrolled inputs with concrete code, plus companions on `defaultValue` and on extending the controlled idea beyond form inputs.
React Stateful vs Stateless Components: Two Explanations Quiz
Two explanations of the stateful/stateless (smart vs presentational) split, plus companions on hooks-era state in function components and on testability trade-offs.
React Code-Splitting: Two Explanations Quiz
Two explanations of code-splitting (bundler-level vs `React.lazy` + `Suspense`) plus companions on preloading routes and on splitting non-component utilities.
React Hooks API Tour Quiz
Six drills covering core hooks: a what-is-a-hook intro plus targeted exercises on useState, useRef, useLayoutEffect, useMemo, and useReducer with runnable examples.
React HOC for Conditional Render (Auth-Aware): Two Approaches Quiz
Two approaches to a conditional-render HOC for authentication (props-based gate vs context-based gate), plus companions on the hook equivalent and on the HOC return-type contract.
React Portals: Two Explanations Quiz
Two explanations of React portals (mechanics and use cases, plus event bubbling through the virtual tree) with companions on a Modal implementation and a portal-aware focus trap.
React Auto-Focus With Refs: Two Approaches Quiz
Two approaches to auto-focusing an input in React (`useRef` + `useEffect` vs the native `autoFocus` prop), plus companions on focusing after async state and on focusing inside a portal.
Community
A Redux + redux-saga Wiring I Still Reach For
redux-saga still earns its keep when async workflows get tangled. The wiring I copy-paste into legacy codebases, plus the takeEvery vs takeLatest decision and the canonical fetch saga.
Server Components vs Client Components: When Each Wins
Server Components are the new default; Client Components are for interactivity and state. The boundary between them is where most beginner Next.js bugs live.
The mapStateToProps / mapDispatchToProps Cheatsheet I Wish I Had In 2018
Every React + Redux codebase from before hooks revolves around connect. Three accordions of the wiring I keep paged in for inheriting one of those repos.
Why My Context Provider Was Re-rendering Everything
We added a flame-graph and saw every consumer of `<UserContext>` re-rendering on every keystroke in a sibling. The fix took two days to isolate and three lines to ship.
The React Bugs I Keep Finding in Pull Requests
I review React PRs all week. These 5 bugs keep showing up: a memo that does nothing, a useCallback hiding the real fix, a SyntheticEvent that vanishes, a stale closure interval, and a batching surprise. Each one is the actual diff I left.
State Management: Zustand, Redux, and Context Compared
Three options, three sweet spots. Zustand is my default for client state, Context for low-frequency tree-wide values, Redux only for the cases that earn it.
The "Component Switch" Pattern I Use Instead of Big Render Trees
Big if/else ladders that pick a component by a tag are unreadable by the third branch. The pattern I use instead is a tiny lookup registry. Three accordions on shipping it.
useElementSize With ResizeObserver
Measuring a DOM node's width and height in React without listening to `window.resize`. Uses `ResizeObserver` so it fires for layout-driven changes (sidebar toggling, font load, parent flex) too.
The React Form Validation Traps I Keep Stepping On
Hand-rolled forms in React look easy until they meet real users. These 5 traps are the ones I keep regressing on: the empty-input case, controlled vs uncontrolled, when to stop hand-rolling, async race conditions, and the accessibility bit nobody catches in review.
Next.js App Router Quirks I Keep Mixing Up
Five App Router gotchas I keep tripping over six months into Next.js 15. Each one is paired with the exact mental model that finally made it click, in TypeScript.
Four Things I Forget About Create-React-App Every Year
Cheat sheet for the CRA quirks that keep coming back. Absolute imports via jsconfig, the HTTPS dev flag, the registerServiceWorker mystery, and the REACT_APP_ env var rules.
Batch and Coalesce Fetch Calls in React
Twenty cards on a page each ask for /api/users/:id and you cut server load 20x with this 30-line dataloader. The batch fires on the next microtask; same id never goes over the wire twice.
React useEffect: The Five Mistakes I Stopped Making
useEffect is for synchronizing with external systems, not for sequencing state. Five concrete mistakes I keep finding in PRs, with the fixes that replaced them.
The HOC + Render Props Patterns I Still Read in Legacy Repos
Hooks made HOCs and render props optional, but pre-2019 codebases still ship them. Four patterns to recognize when you inherit a Redux-era React app.
Three React Router v4 Recipes I Inherit With Old Codebases
RRv4 still survives in long-running codebases. Three recipes I keep paged in: programmatic navigation via withRouter, query parsing, and a custom history singleton for non-React callers.
The Frontend-Only Loop I Coach People Through
Five rounds I rehearse with frontend candidates: a DOM puzzle, a CSS layout, a state management drill, an accessibility audit, and a rendering performance question. JavaScript throughout, framework-agnostic where possible.
The Five Tiny React Patterns I Type Without Thinking
Cheat sheet of the small React tricks I keep typing. Inline-style composition, args-to-handlers, SVG-as-component, and a JSON debug helper that has saved me three Saturdays.
The Observer Pattern and Why React Rediscovered It
Observer is the pattern most engineers think they know, until they look at React's render loop, signals, or RxJS and realize each one is a different observer dialect. The shape, the variants, and the gotchas.
How I Stopped Mutating Nested State in React
The bug we shipped: a deeply nested form state was being updated in place, and React refused to re-render. Here is the 25-line `setIn` helper I now reach for instead of Immer.
useFormField Hook With Field-Level Validation
A field-scoped form hook for the cases where react-hook-form is overkill. Tracks value, touched, blur, and an async validator with a single race-safe in-flight token.
SSR, CSR, SSG, ISR: Pick the Right One
Four rendering strategies, four cost profiles. Pick by data freshness and personalization needs, not by which acronym sounds most modern.
React Server Components Mental Model Quiz
A 5-question quiz that builds the right mental model for React Server Components: where code runs, what can cross the network, when client boundaries cost you, and where async lives.
Frontend Engineer Loop at a Design-Centric Company
A 5 round frontend loop at a design-centric Series C SaaS. The CSS round, the rendering round, the design-system round, and what each one was actually grading.
Windowing a 10k Row List Without react-window
We had a 10k row list freezing scroll. react-window worked but was overkill for our shape. Here is the 60 line virtualizer we shipped instead.
useOptimisticMutation Hook With Rollback
My take on optimistic UI before React 19's `useOptimistic` was usable. The hook applies the change locally, fires the network call, and rolls back on failure with the original snapshot intact.
Route-Level Code Splitting With React.lazy
Our initial bundle was 2.1MB. Splitting routes via React.lazy plus Suspense dropped it to 340KB on first paint. Three accordions on how I wire it.
useCommandK Palette Hook
The cmd-k palette hook I wire into every internal tool. Owns global keyboard shortcuts, fuzzy match, arrow-key navigation, and a focus trap, with no external dependencies.
When `memo` Actually Stops a Re-render (and When It Does Not)
I once added React.memo everywhere and renders barely changed. Memo only works under specific conditions, and outside those it is dead weight. Three accordions on the trap and the fix.
useState Batching and the Stale Closure Trap
React batches state updates, and that interacts badly with closures over old state. The functional updater form fixes most cases, but knowing why is what saves the rest.
useLatest Ref: The Anti-Stale-Closure Pattern
The five-line hook I reach for whenever an effect, a setTimeout, or an external subscription needs to call back into the latest value of a prop or state without re-binding.
The CSS-in-JS Tradeoffs I Keep Explaining to Juniors
Five conversations I keep having: the styling-approach overview, build-time vs runtime CSS-in-JS, CSS Modules vs Tailwind, the styled-components performance trap I keep flagging, and when to walk back to plain CSS.
The React Context Traps I Keep Stepping On
I have lost the same Context fight on three different teams. These are the 5 traps I now check for in every Provider before approving the PR, with the rewrites that actually stop the re-render storm.
The Theme-Switcher Context I Drop Into Every App
The drop-in `<ThemeProvider>` I keep in my dotfiles. CSS variables, `prefers-color-scheme` integration, and `localStorage` persistence in about 60 lines.
The Three Ref-Driven Scroll Hooks I Actually Use
Four ref recipes that earn their keep: `scrollIntoView`, deps-driven scroll-to-top, multi-target callback refs in a Map, and the `forwardRef` + `useImperativeHandle` escape hatch.
What I Ask Juniors Before Extending an Offer
The four questions I lean on when I am the last interviewer for a junior loop. They are not trick questions: each one tells me whether the candidate has actually built something or only studied for the interview.
useInView Hook With Hysteresis
An IntersectionObserver-based `useInView` that does not flip on/off when an element straddles the viewport edge. Uses two thresholds (enter and exit) so analytics events fire once per real visibility.
useUndoRedo Hook With Bounded History
The custom hook I drop in whenever an editor screen needs cmd+z. Gives you `undo`, `redo`, `set`, and a hard cap on memory so a long session does not balloon the heap.
