devsetswww.devsets.com/en/topics/react/notes
React quick reference for interviews
The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.
Components and JSX
- Component.
- A function that returns JSX. The name starts with a capital letter. It must be pure: the same props and state give the same result, with no side effects during render.
- JSX.
- Syntax that compiles to
jsx()calls (formerlyReact.createElement). Expressions go in{}, attributes areclassNameandhtmlFor, and there is one root element or a fragment<>...</>. - Conditional rendering.
cond && <A />, a ternary, or an earlyreturn null. With&&, a0on the left is rendered as text.- Lists and keys.
items.map((i) => <Row key={i.id} />). A key must be stable and unique among siblings. An index as key mixes up state when items are inserted or reordered.- Rules of Hooks.
- Call hooks only at the top level of a component or custom hook: not in conditions, loops or after an early
return. The exception isuse. - Custom hook.
- A
useSomethingfunction that reuses stateful logic. Each call has its own state; to share state, lift it up or use context.
Props and state
- Props.
- Read-only input from the parent. Data flows down, events flow up through callbacks like
onChange. - useState.
- The component's memory. The setter schedules a new render; the variable in the current render doesn't change.
- Functional update.
setCount((c) => c + 1)when the next value depends on the previous one, for example several updates in a row.- Batching.
- Several
setStatecalls in one event cause one render. Since React 18 this also applies in timeouts, promises and native handlers. - Immutability.
- Create a new object or array:
setUser({ ...user, name }). A mutated object with the same reference doesn't trigger a render. - Derived state.
- Whatever can be computed from props or state is computed during render, not stored in a separate state.
- Lifting state up.
- Shared state lives in the nearest common parent and goes down as props.
// add
setItems((prev) => [...prev, item]);
// remove
setItems((prev) => prev.filter((i) => i.id !== id));
// update
setItems((prev) =>
prev.map((i) => (i.id === id ? { ...i, done } : i)),
);Rendering
- When it renders.
- On mount, when its own state changes, when its parent renders (children render too, even with the same props) and when a context it reads changes.
- Render and commit.
- Render calls components and builds a new tree; commit applies the minimal changes to the DOM.
- Reconciliation.
- Trees are compared by element type and key. A different type at the same place remounts the subtree and its state is lost. Changing
keyresets a component on purpose. - Strict Mode.
- In development only, it calls components twice and runs effects as mount, unmount, mount, to expose impure code and missing cleanup.
Effects
- useEffect.
- Syncs a component with an external system after paint: subscriptions, timers, network, browser APIs. The returned cleanup runs before the next effect and on unmount.
- Dependencies.
[]runs once after mount, no array runs after every render. List every reactive value used inside;eslint-plugin-react-hookschecks this.- useLayoutEffect.
- Runs before paint. Use it to measure layout and avoid flicker.
- You might not need an effect.
- Computing data for render and reacting to a click belong in render and in the event handler, not in an effect.
- useEffectEvent.
- Since React 19.2: a function that reads the latest props and state inside an effect without adding them to the dependencies.
- Race conditions.
- A request can finish after a newer one. Abort it in cleanup with
AbortControlleror ignore the stale result with a flag.
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${id}`, {
signal: controller.signal,
})
.then((r) => r.json())
.then(setUser)
.catch(() => {});
return () => controller.abort();
}, [id]);Refs
- useRef.
- A mutable
{ current }object that lives across renders. Changing it doesn't cause a render. For DOM nodes, timer ids and previous values. - Not during render.
- Don't read or write
ref.currentduring render, except for lazy initialization. Do it in effects and handlers. - ref as a prop.
- In React 19, function components receive
refas a regular prop, andforwardRefis no longer needed. A ref callback can return a cleanup. - useImperativeHandle.
- Exposes a limited API to the parent, for example only
focus(), instead of the whole DOM node.
Context and reducer
- Context.
createContext, then<ThemeContext value={...}>(in React 19; earlierThemeContext.Provider) anduseContext(ThemeContext)oruse(ThemeContext).- Context re-renders.
- Every consumer renders when the value changes. Memoize the value object or split context into several smaller ones.
- Not a state manager.
- Context passes data down the tree. For global state that changes often, Zustand, Redux Toolkit or Jotai are a better fit.
- useReducer.
- For state with many transitions: a pure function
(state, action) => newState. Logic moves out of the component and is easy to test.
Performance
- React.memo.
- Skips a render if props are shallowly equal. It only helps when the props really stay the same between renders.
- useMemo and useCallback.
- Cache a computed value and a function between renders. Useful for props of memoized children and for effect dependencies, not for everything.
- React Compiler.
- Stable since 2025. It memoizes components and values at build time, so manual
useMemoanduseCallbackare rarely needed. It requires code that follows the Rules of React. - Transitions.
useTransitionandstartTransitionmark an update as non-urgent, so typing stays responsive.useDeferredValuegives a copy of a value that lags behind.- Code splitting.
lazy(() => import('./Page'))inside<Suspense fallback={...}>loads code when it's needed.- Long lists.
- Thousands of rows are virtualized: only visible rows are rendered (TanStack Virtual, react-window).
- Measure first.
- Find slow components with the React DevTools Profiler before optimizing.
React 19
- Actions.
- Async functions run in a transition.
<form action={fn}>handles the pending state, errors and form reset. - useActionState.
const [state, formAction, isPending] = useActionState(action, initial)- the action's result and its status.- useFormStatus.
- In a child component of a form, returns
pendingand the submitted data, for example to disable the button. - useOptimistic.
- Shows the expected result right away and rolls back if the request fails.
- use.
- Reads a promise (suspends until it resolves) or a context. Unlike other hooks, it can be called in conditions.
- Metadata.
<title>,<meta>and<link>inside components are moved into<head>.- Activity.
- Since React 19.2:
<Activity mode="hidden">hides part of the UI while keeping its state, for example in tabs.
Server Components
- Server Components.
- Render on the server or at build time and ship no JS. They can be
asyncand read a database directly, but have no state, effects or event handlers. - 'use client'.
- Marks a boundary: this module and everything it imports become client components. A server component can be passed into a client one as
children. - 'use server'.
- Marks Server Functions that the client calls with a POST request. They are public endpoints: validate input and check permissions.
- RSC vs SSR.
- SSR renders client components to HTML for the first load and then hydrates them. Server Components are a kind of component that never hydrates.
Errors, Suspense, portals
- Error boundary.
- A class component with
getDerivedStateFromErrorandcomponentDidCatch, or thereact-error-boundarypackage. It doesn't catch errors in event handlers or async code. - Suspense.
- Shows a fallback while its children wait for code (
lazy) or data (use, framework loaders). - Portals.
createPortal(children, node)renders into another DOM node, for example for a modal. Events still bubble through the React tree.
Common pitfalls
- Stale closure: an interval or handler sees an old value. Use a functional update or correct dependencies.
- An object, array or function created during render is new every time, so an effect with it in the dependencies runs after every render.
{count && <List />}renders0when the count is zero. Writecount > 0 &&.items.push(x); setItems(items)doesn't cause a render: the reference is the same.key={index}on a list that changes order, orkey={Math.random()}, which remounts the item on every render.- Calling
setStatedirectly in render causes an infinite loop. - Copying props into state: the state doesn't update when props change. Compute the value or reset with
key. - Reading state right after
setStategives the old value: the new one arrives in the next render. - An effect without cleanup leaves duplicate subscriptions and timers.