Appearance
React Patterns
30. What are error boundaries?
The short answer
An error boundary is a component that catches errors thrown while rendering any component below it, shows a fallback UI instead of a blank screen, and can log the error. Without one, an error anywhere during rendering unmounts the whole app. They do not catch errors in event handlers, in async code such as a failed fetch callback, or in the boundary itself. They are still written as class components, or with the react-error-boundary library.
tsx
import { ErrorBoundary } from 'react-error-boundary'
function WidgetError({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
return (
<div role="alert">
<p>Recommendations could not load.</p>
<button onClick={resetErrorBoundary}>Try again</button> {/* (1) */}
</div>
)
}
function ProductPage() {
return (
<>
<ProductDetails />
<ErrorBoundary FallbackComponent={WidgetError} // (2)
onError={(error, info) => reportError(error, info.componentStack)}> {/* (3) */}
<Recommendations />
</ErrorBoundary>
</>
)
}- Reset re-renders the children, giving them another chance.
- A boundary around one widget: if recommendations crash, the product details and the "Buy" button still work.
- Log the error with the component stack to your error tracking service.
What boundaries catch, and what they do not:
| Caught | Not caught |
|---|---|
| Errors during render | Errors in onClick and other event handlers |
| Errors in lifecycle methods and effects' setup | Errors in setTimeout or promise callbacks |
| Errors in constructors of children | Errors thrown inside the boundary itself |
For event handlers and async code, use try/catch and set error state, or let the data library handle it. To send an async error to the nearest boundary, set it in state and throw it during the next render; react-error-boundary gives you a showBoundary function for this.
Where to place them: one at the top of the app as a last resort, one per route so one broken page does not break navigation, and around independent widgets.
31. What are portals?
The short answer
A portal renders a component's output into a different DOM node, outside its parent's DOM element, while keeping it in the same place in the React tree. createPortal(children, document.body) is used for modals, tooltips, dropdowns and toasts, which must escape a parent's overflow: hidden or stacking context to appear on top. Events from inside a portal still bubble through React parents as if it were rendered in place, and context still works.
tsx
import { createPortal } from 'react-dom'
function ConfirmDialog({ open, onClose, children }: { open: boolean; onClose: () => void; children: React.ReactNode }) {
if (!open) return null
return createPortal( // (1)
<div className="backdrop" onClick={onClose}>
<div role="dialog" aria-modal="true" className="dialog" onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>,
document.body, // (2)
)
}
function CartItem() {
const [confirming, setConfirming] = useState(false)
return (
<li className="cart-item"> {/* overflow: hidden here */}
<button onClick={() => setConfirming(true)}>Remove</button>
<ConfirmDialog open={confirming} onClose={() => setConfirming(false)}>
Remove this item from your basket?
</ConfirmDialog>
</li>
)
}createPortalrenders the dialog's DOM somewhere else.- Into
document.body, so the cart item'soverflow: hiddencannot clip it.
Accessibility still matters: a modal should move focus into the dialog, trap it there, close on Escape and return focus when closed. The native <dialog> element with showModal() handles much of this, and component libraries do it for you.
32. What is composition, and why does React prefer it over inheritance?
The short answer
Composition means building components by putting other components inside them, usually through children or other props that accept elements, instead of creating subclasses. A Card does not need a ProductCard extends Card; it accepts whatever content you place inside it. This keeps components small and flexible: the outer component controls layout and behaviour, the caller controls content. React's own documentation says it has never found a case that needed inheritance between components.
tsx
function Panel({ title, actions, children }: {
title: string
actions?: React.ReactNode // (1)
children: React.ReactNode // (2)
}) {
return (
<section className="panel">
<header>
<h2>{title}</h2>
{actions}
</header>
<div className="panel-body">{children}</div>
</section>
)
}
function OrdersPanel() {
return (
<Panel title="Recent orders" actions={<a href="/orders">View all</a>}> {/* (3) */}
<OrderList limit={5} />
</Panel>
)
}- A "slot" prop: the caller decides what appears in the header.
children: whatever is placed between the tags.- The same
Panelserves orders, invoices or anything else, with no subclass.
Variations you will see:
| Pattern | Example |
|---|---|
children | <Modal>…</Modal> |
| Named slots | <Layout sidebar={<Nav />} main={<Page />} /> |
| Compound components | <Tabs><Tabs.List /><Tabs.Panel /></Tabs> sharing state through context |
| Specialisation by wrapping | function DangerButton(props) { return <Button variant="danger" {...props} /> } |
33. What are higher-order components and render props, and why did hooks replace most of them?
The short answer
A higher-order component is a function that takes a component and returns a new component with extra behaviour, such as withAuth(Dashboard). A render prop is a prop that is a function, which a component calls to decide what to render, such as <MouseTracker render={(pos) => …} />. Both were ways to share stateful logic before hooks. Hooks do the same job more simply, without extra wrapper layers in the tree, unclear prop sources or naming clashes, so modern code uses custom hooks.
The same logic three ways, knowing whether the window is narrow:
tsx
// 1. Higher-order component
function withIsMobile<P>(Component: React.ComponentType<P & { isMobile: boolean }>) {
return function Wrapped(props: P) {
const isMobile = useMediaQuery('(max-width: 600px)')
return <Component {...props} isMobile={isMobile} />
}
}
const Header = withIsMobile(BaseHeader)
// 2. Render prop
function IsMobile({ children }: { children: (isMobile: boolean) => React.ReactNode }) {
return <>{children(useMediaQuery('(max-width: 600px)'))}</>
}
<IsMobile>{(isMobile) => (isMobile ? <BurgerMenu /> : <NavBar />)}</IsMobile>
// 3. Custom hook: the modern way
function Header2() {
const isMobile = useMediaQuery('(max-width: 600px)')
return isMobile ? <BurgerMenu /> : <NavBar />
}| Problem with older patterns | How hooks avoid it |
|---|---|
| "Wrapper hell": many layers in DevTools | No extra components |
| Unclear where a prop came from | The hook call is visible in the component |
| Prop name clashes between HOCs | Each hook returns values you name yourself |
| Logic tied to rendering | Hooks return data; you decide what to render |
Where HOCs and render props still appear: older libraries, and cases like route guards or analytics wrappers that genuinely wrap a whole component. Knowing them helps you read existing code.
34. How do you handle forms in React?
The short answer
For a small form, controlled inputs with useState and a submit handler are enough. For real forms with many fields and validation, use a form library, usually React Hook Form, which keeps inputs uncontrolled for speed and tracks values, errors and touched state for you, together with a schema validator such as Zod, so the same rules describe the data and its TypeScript type. Always validate again on the server, because client-side validation can be bypassed.
tsx
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
const AddressSchema = z.object({ // (1)
fullName: z.string().min(2, 'Please enter your name'),
postcode: z.string().regex(/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i, 'Enter a valid UK postcode'),
phone: z.string().optional(),
})
type Address = z.infer<typeof AddressSchema>
function AddressForm({ onSave }: { onSave: (a: Address) => Promise<void> }) {
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<Address>({
resolver: zodResolver(AddressSchema), // (2)
})
return (
<form onSubmit={handleSubmit(onSave)} noValidate> {/* (3) */}
<input {...register('fullName')} aria-invalid={!!errors.fullName} /> {/* (4) */}
{errors.fullName && <p role="alert">{errors.fullName.message}</p>}
<input {...register('postcode')} />
{errors.postcode && <p role="alert">{errors.postcode.message}</p>}
<button disabled={isSubmitting}>{isSubmitting ? 'Saving…' : 'Save address'}</button>
</form>
)
}- One schema holds the rules and produces the TypeScript type (question 79).
- The resolver runs the schema on submit and on change, and maps problems to fields.
handleSubmitvalidates first, and callsonSaveonly with valid, typed data.registerconnects an input by name, without making it controlled, so typing does not re-render the whole form.
Good form habits: show errors next to the field and connect them for screen readers, disable the button while submitting to stop double orders, keep the user's input after a server error, and reuse the same Zod schema on the server where possible. React 19's form actions can handle simple forms without a library (question 22).
35. How does client-side routing work in React?
The short answer
In a single-page app, the browser loads one HTML page, and a router library, such as React Router or TanStack Router, decides which components to show based on the URL. Clicking a router Link changes the URL with the History API without a full page reload, and the router renders the matching route. The server must return the same index.html for every route path, otherwise refreshing a page like /orders/42 gives a 404.
tsx
import { createBrowserRouter, RouterProvider, Link, useParams } from 'react-router'
const router = createBrowserRouter([
{
path: '/',
element: <Layout />, // (1)
children: [
{ index: true, element: <Home /> },
{ path: 'orders', element: <OrderList /> },
{ path: 'orders/:orderId', element: <OrderDetails />, // (2)
loader: ({ params }) => fetchOrder(params.orderId!) }, // (3)
{ path: '*', element: <NotFound /> },
],
},
])
function OrderDetails() {
const { orderId } = useParams() // (4)
return <h1>Order {orderId} <Link to="/orders">Back</Link></h1>
}
export default function App() { return <RouterProvider router={router} /> }- A layout route renders shared parts, such as the header, and an
<Outlet />for the child route. - A dynamic segment,
:orderId. - A loader fetches data before the route renders, so data and code load in parallel.
- Reading the URL parameter in the component.
Why refresh gives 404 on a static host: the server looks for a file called /orders/42, which does not exist. Configure it to serve index.html for unknown paths, a "SPA fallback" (question 60).
Protecting routes: a wrapper or loader that checks the session and redirects to /login improves the experience, but real protection is the API refusing unauthenticated requests (question 36).
36. How should a React SPA handle authentication and tokens?
The short answer
The safest common approach is to keep tokens out of JavaScript entirely: the backend, or a backend-for-frontend, holds the session and sets an HttpOnly, Secure, SameSite cookie, so the browser sends it automatically and script, including injected script, cannot read it. If the SPA must hold an access token, keep it in memory only, make it short-lived, and refresh it through an HttpOnly refresh-token cookie. Avoid localStorage for tokens, because any XSS can steal them.
| Where the token lives | Readable by injected script | CSRF risk | Survives reload |
|---|---|---|---|
HttpOnly cookie | No | Yes: needs SameSite and CSRF protection | Yes |
| Memory, a JS variable | Yes, while the page is open | No | No: refresh needed |
localStorage, sessionStorage | Yes, at any time | No | Yes |
A typical in-memory pattern, when the API is on another domain and expects bearer tokens:
tsx
let accessToken: string | null = null // (1)
async function apiFetch(path: string, init: RequestInit = {}) {
const send = () => fetch(path, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${accessToken}` },
})
let res = await send()
if (res.status === 401) { // (2)
const r = await fetch('/auth/refresh', { method: 'POST', credentials: 'include' }) // (3)
if (!r.ok) { window.location.assign('/login'); throw new Error('session expired') }
accessToken = (await r.json()).accessToken
res = await send()
}
return res
}- In memory only, never written to storage. Lost on reload, by design.
- An expired access token comes back as
401. - The refresh token is an
HttpOnlycookie, sent withcredentials: 'include', so the app gets a new short-lived access token without ever seeing the refresh token.
What the SPA must never do: treat hiding a button as security. The UI can hide admin links for convenience, but the API must check permissions on every request. Where to keep tokens in a browser app is covered in token storage.
37. How does React protect against XSS, and when does it not?
The short answer
Cross-site scripting, XSS, is when an attacker gets their script to run in your page, for example through a product review containing <script>. React escapes every value you place in JSX with {}, so text from users is shown as text, never run as HTML. The protection is bypassed by dangerouslySetInnerHTML, by javascript: URLs in href, by building HTML strings yourself, and by putting user input into eval or script tags. Sanitise any HTML you must render, and add a Content Security Policy.
tsx
function Review({ text, website }: { text: string; website: string }) {
return (
<article>
<p>{text}</p> {/* (1) safe */}
<div dangerouslySetInnerHTML={{ __html: text }} /> {/* (2) dangerous */}
<a href={website}>Reviewer's site</a> {/* (3) check it */}
</article>
)
}- Escaped:
<img src=x onerror=alert(1)>is shown literally as text. - Raw HTML: an attacker's review can run any script, with the user's session.
- A
javascript:alert(1)URL runs code when clicked. React warns about it, but only validating the URL, allowing onlyhttps:andhttp:, makes it safe.
When you really need HTML, such as content from a rich text editor, sanitise it first:
tsx
import DOMPurify from 'dompurify'
function ProductDescription({ html }: { html: string }) {
const clean = useMemo(() => DOMPurify.sanitize(html, { USE_PROFILES: { html: true } }), [html])
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
function safeUrl(url: string) {
try {
const u = new URL(url)
return u.protocol === 'https:' || u.protocol === 'http:' ? u.href : '#'
} catch {
return '#'
}
}Defence in depth: a Content Security Policy header that forbids inline scripts limits the damage even when a bug slips through, and keeping tokens out of reach of JavaScript means a successful XSS cannot steal them (question 36). XSS, CSP and the related headers are covered in the security module.
38. How do you fetch data in a React component correctly?
The short answer
Fetching inside useEffect by hand must handle four things: loading and error states, cancelling or ignoring a response that arrives after the inputs changed, which otherwise shows the wrong data, cleaning up when the component unmounts, and avoiding duplicate requests. Because that is easy to get wrong, most apps use a data library such as TanStack Query or a framework's loaders, which add caching, de-duplication, retries and background refresh on top.
The race condition:
Doing it by hand, correctly:
tsx
function OrderDetails({ orderId }: { orderId: string }) {
const [state, setState] = useState<{ status: 'loading' | 'error' | 'ready'; order?: Order }>({ status: 'loading' })
useEffect(() => {
const controller = new AbortController() // (1)
setState({ status: 'loading' })
fetch(`/api/orders/${orderId}`, { signal: controller.signal })
.then((r) => { if (!r.ok) throw new Error(String(r.status)); return r.json() })
.then((order: Order) => setState({ status: 'ready', order }))
.catch((err) => { if (err.name !== 'AbortError') setState({ status: 'error' }) }) // (2)
return () => controller.abort() // (3)
}, [orderId])
if (state.status === 'loading') return <Spinner />
if (state.status === 'error') return <p>Could not load the order.</p>
return <OrderView order={state.order!} />
}- One controller per effect run.
- An abort is not a real error, so ignore it.
- When
orderIdchanges, the cleanup aborts the old request before the new effect starts, so A can never overwrite B.
The same with TanStack Query:
tsx
function OrderDetails2({ orderId }: { orderId: string }) {
const { data, isPending, isError } = useQuery({
queryKey: ['order', orderId],
queryFn: ({ signal }) => fetch(`/api/orders/${orderId}`, { signal }).then((r) => r.json()),
})
if (isPending) return <Spinner />
if (isError) return <p>Could not load the order.</p>
return <OrderView order={data} />
}The library keys results by ['order', orderId], so a late response for A is stored under A and never shown for B, and it adds caching, retries and refresh on focus (question 47).