Tags

Hooks

Hooks

0 lessons
14 code snippets
11 question banks
21 community items

hooks

Code Snippets

14 snippets
Code Snippet

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.

JavaScript
react
hooks
performance-optimization
code-template

220

7

Easy
Code Snippet

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.

JavaScript
react
hooks
performance-optimization
code-template

927

5

Easy
Code Snippet

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.

JavaScript
react
hooks
js-local-storage
code-template

496

4

Easy
Code Snippet

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.

JavaScript
react
hooks
code-template
references

203

6

Easy
Code Snippet

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).

JavaScript
react
hooks
code-template
utility

630

16

Easy
Code Snippet

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.

JavaScript
react
hooks
code-template
references

656

14

Easy
Code Snippet

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.

JavaScript
react
hooks
code-template
performance-optimization

1.1k

33

Medium
Code Snippet

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.

JavaScript
react
hooks
code-template
js-event-loop

364

1

Medium
Code Snippet

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.

JavaScript
react
hooks
code-template
js-event-loop

269

6

Medium
Code Snippet

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.

JavaScript
react
hooks
code-template
css-media-queries

720

5

Medium
Code Snippet

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.

JavaScript
react
hooks
code-template
js-web-apis

803

21

Medium
Code Snippet
Premium

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.

JavaScript
react
hooks
code-template
js-fetch-api

1k

31

Hard
Code Snippet
Premium

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.

JavaScript
react
hooks
code-template
performance-optimization

354

1

Hard
Code Snippet

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.

JavaScript
react
hooks
conditionals

806

25

Easy

Question Banks

11 items
Question Bank

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.

JavaScript
quiz
react
hooks
interview-prep

355

9

Medium
Question Bank

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.

JavaScript
quiz
react
hooks
fundamentals

208

1

Easy
Question Bank

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.

JavaScript
quiz
react
hooks
js-dom

491

4

Medium
Question Bank

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.

JavaScript
quiz
react
hooks
state-machine

587

11

Easy
Question Bank

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.

JavaScript
quiz
react
hooks
interview-prep

1.1k

17

Medium
Question Bank

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.

JavaScript
quiz
react
hooks
error-handling

570

16

Medium
Question Bank

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.

JavaScript
quiz
react
hooks
js-fetch-api

422

3

Medium
Question Bank

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.

JavaScript
quiz
react
references
hooks

222

2

Medium
Question Bank

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.

JavaScript
quiz
react
hooks
js-dom

977

16

Easy
Question Bank
Premium

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.

JavaScript
quiz
react
hooks
interview-prep

899

7

Hard
Question Bank

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.

JavaScript
quiz
react
references
hooks

1k

28

Medium

Community

21 items
Article

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.

react
frontend
performance
hooks

245

6

4.0 (10)

May 6, 2026

by @mianair

Code Snippet

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.

JavaScript
react
hooks
memoization
performance-optimization

538

5

4.4 (12)

May 1, 2026

by @amiraprice

Question Bundle
$14.99

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.

JavaScript
react
hooks
interview-prep
error-handling

1k

27

4.2 (15)

Apr 28, 2026

by @ethandubois

Article

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.

react
frontend
hooks
state-machine

952

23

Apr 28, 2026

by @folakemansour

Code Snippet

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.

JavaScript
react
hooks
design-patterns

780

25

4.5 (8)

Apr 9, 2026

by @diegonguyen

Code Snippet

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.

JavaScript
react
hooks
performance-optimization
resize-observer

977

30

4.4 (8)

Apr 7, 2026

by @lilykelly

Question Bundle
Free

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.

JavaScript
react
hooks
js-dom
interview-prep

795

3

4.2 (15)

Apr 4, 2026

by @zurihayes

Article

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.

react
hooks
frontend
debugging

962

7

4.3 (11)

Mar 10, 2026

by @yunatorres

Code Snippet

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.

JavaScript
react
hooks
js-spread-rest

482

8

4.3 (12)

Feb 28, 2026

by @ryanjoshi

Code Snippet

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.

JavaScript
react
hooks
immutability

1.1k

17

4.4 (14)

Feb 23, 2026

by @kwamehenderson

Code Snippet

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.

JavaScript
react
hooks
code-template
error-handling

729

13

4.5 (10)

Feb 23, 2026

by @leoeriksson

Code Snippet

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.

JavaScript
react
hooks
error-handling
optimistic-ui

582

8

4.7 (9)

Jan 28, 2026

by @laylabauer

Code Snippet

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.

JavaScript
react
hooks
accessibility
command-palette

1.1k

6

4.4 (13)

Jan 21, 2026

by @zurihayes

Code Snippet

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.

JavaScript
react
hooks
memoization
performance-optimization

978

7

4.2 (12)

Jan 8, 2026

by @ananyaadeyemi

Article

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.

react
hooks
frontend
debugging

633

20

4.2 (9)

Dec 27, 2025

by @rinahassan

Code Snippet

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.

JavaScript
react
hooks
code-template
utility

851

20

4.4 (8)

Dec 24, 2025

by @petrawilson

Question Bundle
$12.99

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.

JavaScript
react
hooks
performance-optimization
interview-prep

799

24

4.4 (11)

Dec 2, 2025

by @felixhaddad

Code Snippet

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.

JavaScript
react
hooks
css-variables

654

10

4.3 (13)

Nov 30, 2025

by @kiranpatel

Code Snippet

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.

JavaScript
react
hooks
references
js-dom

618

12

4.4 (15)

Nov 26, 2025

by @rajtanaka

Code Snippet

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.

JavaScript
react
hooks
performance-optimization
intersection-observer

992

10

4.3 (14)

Nov 25, 2025

by @ethanhadid

Code Snippet

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.

JavaScript
react
hooks
undo-redo
utility

622

12

4.2 (12)

Nov 21, 2025

by @sanjayward