Custom hooks
React chapter 14 · useControlled, useForkRef, useMediaQuery, useEventCallback · source: packages/mui-utils/src
The problem
The same open/close logic is copy-pasted into every panel. When a fix is needed, you must remember every copy, and one always gets missed.
The pattern that fixes it
Move the logic into a function named useX, call it at the top of each component, and return the state plus its actions. Fix it once and every caller gets the fix.
In plain words
A custom hook is just a function that uses other hooks and starts with use. It lets you package "state plus the rules around it" and reuse it, the way you reuse any other function.
Instead of writing the same recipe card by hand for every kitchen and fixing each card separately, you keep one master recipe. Each kitchen gets its own pot, but they all follow the same steps.
Terms
- custom hook
- Your own function whose name starts with use and that calls other hooks such as useState.
- rules of hooks
- Call hooks at the top level of a component or another hook, never inside if, loops or nested functions, so React can match them up by order.
- return shape
- What the hook gives back, like { open, toggle, close }. Keep it stable so callers do not break.
Going deeper
How does it work?
A hook is not a special object: React tracks the hook calls made while a component renders, in order. A custom hook simply runs its useState and friends inside the calling component, so each call gets its own private state. Two panels using useDisclosure() share the code but not the data.
When it goes wrong
Calling a hook conditionally breaks the order and React throws errors or mixes up state. A hook that returns a new object or function every render can defeat memo downstream, so wrap returned callbacks in useCallback. A hook that returns JSX is usually a component in disguise. Sharing a hook does not share state; for that you need context or a store.
When NOT to use it, and modern alternatives
Do not extract after one use, or for a single useState line with no rules around it. Extract when logic repeats, when a component mixes unrelated concerns, or when you want to test behavior alone. For data fetching or subscriptions prefer a proven library or useSyncExternalStore. MUI is built this way: useControlled, useForkRef and useMediaQuery are hooks first, components second.
Keep learning
- Previous: useCallback
- Next: useEffectEvent
- Related: memo
- Related: useMemo
- Related: useCallback
- Related: useEffectEvent
- Related: useTransition
- Related: useDeferredValue
Overview
Press Esc here Real life: a settings page with three collapsible panels, each written by copy-paste.
Billing
Reopen all copy C never got the Escape fix
Press Esc on all three: Billing stays open.
The "close on Escape" fix was pasted into two copies and missed the third. With copy-paste, every change is a hunt, and the copies drift apart. Press Press Esc here on each panel. Alerts and Filters close, Billing does not. Press Reopen all and try again with the keyboard: focus a button and hit the real Esc key. Same settings page, now every panel calls one hook. Edit the hook once and watch all three change. The hook's code useDisclosure (no Esc yet) useDisclosure + Esc (one edit)
Press Esc on any panel: all three close.
One edit inside the hook reached every caller. Billing cannot be forgotten, because it has no copy of the logic.
Press Esc on a panel: nothing closes yet.
Open and close each panel on its own: the three calls share code but not state. Now switch to the second option to add Esc in one place. A good custom hook Has one job and a clear name starting with use. Returns a stable shape. Contains behavior, not JSX. Watch out for Calling it inside if or a loop. Expecting two callers to share state. Extracting after only one use. Second example, usePrevious: a hook that remembers what a value was one change ago. Type here none yet Each keystroke moves "now" into "previous". The hook keeps that bookkeeping out of your component. Close Alerts, then press Esc on Filters. Only Filters closes: each call has its own state. Switch the hook to the Esc version without reloading: open panels respond immediately.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.