home
›
cheatsheets
›
frontend_development
›
react
Free to read Every card and diagram, and Quiz me
2
Free account Star cards. Your Quiz me marks are kept, so next time you drill just what you missed
3
Pro All 103 answers on this sheet, My sheet across every topic, and PDFs
A free account keeps your stars and Quiz me marks. Pro adds all 103 answers on this sheet, My sheet across every topic, and PDFs.
/
Read
Quiz me
Comfortable
Compact
My misses 0
Click any code to copy it
Done 0 /0
To review 0
Old way, still asked about
Current way
New since React 19
On this sheet
The model
01 Components & JSX02 Props, state & events03 Hooks & effects04 Context & global state05 Performance06 Forms & inputs07 React 18, 19 & SSR08 Component patterns09 Routing & auth10 Test, build & deploy
The model A component is a function that turns props and state into elements. When either changes, React calls it again and gets new elements. Each render is a snapshot . Its props, state and handlers stay fixed, so a callback that outlives the render still reads the old values. React diffs the new element tree with the last one and writes only the changes to the DOM. React calls this reconciliation , and key tells it which list item is which. Rendering must be pure . Fetching, subscribing and timers go in event handlers or useEffect, never in the component body. Data flows down as props, and a child reports back by calling a function prop. State that two components share lives in their closest common parent. Read top to bottom. React re-runs your component and writes only what changed. useLayoutEffect runs before paint, and useEffect usually after.
Components & JSX what a component is and how JSX works Function and class components Write a component const Hi = ({ name }) => <p>{name}</p>;
Write one as a class class Hi extends React.Component Return JSX from its render method.
Tell an element from a component An element describes UI. A component returns elements.
Tip Hooks give function components state and effects, so new code uses functions. Only error boundaries still need a class.
Trap Start the name with a capital letter. JSX reads <hello /> as an HTML tag.
How React updates the page Say what the virtual DOM is An in-memory copy of the UI that React diffs.
Name React's engine (16+) Fiber. It can pause a render, then commits in one pass.
Mount the app const root = createRoot(el); root.render(<App />);
Mount it the old way ReactDOM.render(<App />, el) Removed in React 19.
Tip react defines components and Hooks. react-dom renders them into the browser DOM.
JSX rules Skip the wrapper div <><A /><B /></>
Say what JSX compiles to React.createElement() Or react/jsx-runtime calls, since React 17.
Tip Write attributes in camelCase, like className and onClick. Close every tag, and put JavaScript in {}.
Trap Only the long form of a fragment takes a key. In a list, write <Fragment key={id}>, not <>.
Lists and conditions A New A key={item.id} Insert New at the top. The key matches A to its old row, so A keeps its state.0: A 0: New 1: A key={index} Rows match by position, so New gets A's state and A starts empty.Render a list todos.map(t => <Todo key={t.id} {...t} />)
Show one of two elements {isLoggedIn ? <Home /> : <Login />}
Reset a child's state <Form key={userId} />
Trap {count && <List />} shows 0 when count is 0. Make the left side a boolean.
Class lifecycle methods Run code after the first render componentDidMount() In Hooks, an effect with empty deps.
Clean up before React removes it componentWillUnmount() In Hooks, the effect's cleanup.
Tip Anything componentDidMount starts, like a timer or a subscription, must stop in componentWillUnmount .
Props, state & events data in, data owned, and user input Props Pass data to a child <Avatar user={user} />
Send data back up to the parent <Search onChange={setQuery} /> The child calls it with the data.
Share state between two siblings Lift it to their closest common parent and pass it down.
State with useState Give a component its own state const [count, setCount] = useState(0);
Update from the previous value setCount(c => c + 1)
Update an object without mutating it setUser({ ...user, name })
Tell props from state Props are read-only inputs. State is the component's own memory.
Tip Never mutate state. React re-renders only when you call the setter with a new value.
Trap Calling setCount(count + 1) twice in one handler adds 1, not 2. Both calls read the same count.
Handle events Run a function on click onClick={handleClick}
Pass an argument to the handler onClick={() => remove(id)}
Tip React passes a SyntheticEvent that works the same in every browser. e.nativeEvent is the browser's own.
Trap onClick={handleClick()} runs the handler during render. Pass the function, not a call.
Hooks & effects effects, refs and the rules Hooks and their rules Name the two rules of Hooks Top level only, and only in components or custom Hooks.
Share stateful logic between components A use function that calls Hooks. Each caller gets its own state.
Tip React matches Hooks by call order. A Hook inside an if shifts every Hook after it.
When an effect runs Mount New id Same id
useEffect(fn) Run after every render
useEffect(fn, []) Run once, after mount
useEffect(fn, [id]) Run again when id changes
the effect runs React skips it
Tip React compares each dependency with Object.is. A new object or function every render counts as a change.
Trap Strict Mode runs setup and cleanup one extra time in development, so even a [] effect runs twice.
Cleanup and layout effects Stop a timer or a subscription return () => clearInterval(id);
Measure before paint useLayoutEffect(fn, [])
Tip React runs the cleanup before the effect runs again, and once more on unmount.
Trap useLayoutEffect blocks painting until it finishes. Keep the work in it short.
Fetch data in an effect Catch a failed request Wrap the await in try and catch, and keep the error in state.
Ignore a response that arrives too late Set an ignore flag in the cleanup, and skip the state update.
Tip Error boundaries don't catch errors in async code, so the effect must catch them.
Trap fetch rejects only on a network failure. Check res.ok, or a 500 looks like success.
Fix a stale closure Re-run the effect with fresh values Add the value to the deps. The cleanup clears the old timer.
Read fresh values without re-running (19.2+) useEffectEvent(fn) Before 19.2, use a ref.
Trap An interval set in an [] effect reads state from the first render forever. Use the updater setCount(c => c + 1) instead.
Refs Focus an input useRef(null) ref.current.focus()
Take a ref as a prop function Input({ ref })
Do the same before React 19 forwardRef((props, ref) => <input ref={ref} />)
Trap Changing ref.current doesn't re-render. Keep anything the screen shows in state.
useReducer Manage state with a reducer useReducer(reducer, init)
Pick it over useState When values change together, or the next depends on the last.
Context & global state share data across the tree Avoid prop drilling Fix it across a few levels Pass the finished child down through the children prop.
Fix it for data many components read Use Context, or a store like Redux or Zustand.
Context Provide a value to everything below <UserContext.Provider value={user}>
Provide it in React 19 <UserContext value={user}>
Read it in any child useContext(UserContext)
Keep the value object stable useMemo(() => ({ user, login }), [user])
Tip Wrap it in a useUser Hook that throws a clear error outside the provider.
Trap Every reader re-renders when the value changes, even inside memo. Split fast and slow values into separate contexts.
Pick a state tool Share state that changes often Redux Toolkit or Zustand.
Cache data from the server TanStack Query or SWR.
Keep state across a page refresh localStorage Read it back in a lazy useState initializer.
Subscribe to a store outside React useSyncExternalStore Pass it subscribe and getSnapshot.
Tip Start with useState, useReducer and Context. In a small app a library only adds setup.
Redux Create the store configureStore({ reducer })
Create it the old way createStore(reducer) Deprecated.
Read state and dispatch actions useSelector(s => s.count) useDispatch()
Tip Redux keeps one store with read-only state. Only a dispatched action changes it, through a pure reducer.
React 18, 19 & SSR new Hooks and server rendering Concurrent rendering Mark an update as non-urgent startTransition(() => setList(l))
Defer a slow list useDeferredValue(query)
Name what React 18 added Concurrent rendering, automatic batching, streaming SSR and useId.
Tip Use useTransition when you own the setter, and useDeferredValue when you only receive the value.
Trap useDeferredValue gains nothing unless the slow component is wrapped in memo.
What React 19 added Run a form action and track its result useActionState(action, init)
Show a change before the server confirms it useOptimistic(todos, addTodo)
Read a promise in render use(promise)
Tip useOptimistic shows the confirmed state again when the action ends, so a failed request reverts itself.
Trap React 19 removed ReactDOM.render, string refs and findDOMNode, and it requires the new JSX transform.
Render on the server Send finished HTML for each request SSR. Fast first paint and good SEO, but more server work.
Build pages once and serve them from a CDN SSG. Content changes only on a rebuild.
Make server HTML interactive hydrateRoot(rootEl, <App />)
Keep a component's code out of the browser A Server Component. It can read the database, but has no state.
Tip Start a file with 'use client' to make its components Client Components, with state and events.
Trap Client and server must render the same HTML. The time or typeof window in render breaks that.
Component patterns reuse markup and logic across components Composition and portals Wrap any content in a generic box {children}
Split data fetching from rendering A container fetches and holds state. A presentational component only renders props.
Render a modal outside the parent's DOM createPortal(children, modalRoot)
Trap A portal's events bubble through its React parents, not its DOM parents. It still reads their context too.
HOCs, render props and compound components Wrap a component to add behaviour withAuth(Panel)
Let the caller decide what to render <Mouse render={pos => <Dot {...pos} />} />
Do it with a Hook useAuth()
Build parts that work as one, like select The parts read the parent's state through context.
Let callers change how a Hook updates state useToggle({ reducer })
Trap Stacked HOCs can clash on prop names and bury the tree in DevTools.
Error boundaries Write a boundary class getDerivedStateFromError shows the fallback, and componentDidCatch logs the error.
Use one without writing a class npm i react-error-boundary
Send an async error to the boundary useErrorBoundary()
Trap Boundaries miss errors in event handlers, async code, server rendering and the boundary itself.
Undo, drag and drop, event bus Add undo and redo A history array and an index. A new edit drops everything after it.
Let a drag target accept a drop onDragOver={e => e.preventDefault()}
Notify components that share no parent Subscribe in useEffect, and return the unsubscribe.
Trap Keep the history and index in one state object, and change it with an updater.
Routing & auth pages, URL data, guarded routes and XSS React Router Map a path to a component <Route path="/users/:id" element={<User />} />
Read :id from the path const { id } = useParams();
Read the query string useSearchParams()
Route on a host you can't configure <HashRouter> URLs look like /#/about.
Tip Params are always strings. Convert numbers yourself, and handle a missing one.
Trap With BrowserRouter, a refresh on /about asks the server for /about. It must return index.html.
Protect routes and users Send signed-out users to the login page <Navigate to="/login" replace />
Store the session In an httpOnly cookie. Scripts can't read it, so XSS can't steal it.
Clean user HTML before you render it DOMPurify.sanitize(raw)
Limit where scripts can load from Content-Security-Policy: script-src 'self'
Tip React escapes text in {}. Only dangerouslySetInnerHTML inserts raw HTML.
Trap A client-side guard only hides screens. The server must check every API request.
Test, build & deploy tests, builds and hosting Test components Find an element the way a user would getByRole('button', { name: /save/i })
Type and click like a real user userEvent.setup() await user.click(btn)
Check a callback was called jest.fn() toHaveBeenCalledWith(1)
Tip Query by role, label or text, not class names. Tests of what users see survive a refactor.
Test async code, Context and Hooks Wait for an element to appear await findByText('Saved')
Replace fetch with a mock global.fetch = jest.fn()
Render inside the provider it needs render(ui, { wrapper: Auth })
Test a Hook on its own renderHook(() => useCounter())
Tip Wrap a Hook's state update in act(), then read result.current.
Start, configure and deploy Start a new app npm create vite@latest my-app -- --template react
Start one with Create React App Deprecated. Use Vite, or a framework like Next.js.
Read an environment variable import.meta.env
Serve client routes after a refresh try_files $uri $uri/ /index.html;
Tip Vite exposes only VITE_ variables to your code, as strings. Compare a flag with 'true'.
Trap Env values end up in the bundle as plain text. Never put secrets in them.
Nothing matches. Try a shorter word, or clear the search.
Practice 108 interview questions Full answers, from beginner to expert.
Found this useful? Pass it on.
Share on LinkedIn
Share on X
Copy link
This sheet stays free. With Pro , you can:
Every answer on this sheet. Read the full answer to all 103 questions it links, not just the 15 free ones.
My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.