HTHyperTransformer AI

Study cards › React & Frontend

React & FrontendInterview questions and answers

← Topics1 / 103
1 / 103 viewed
Question

What is a React component?

Answer

A self-contained, reusable piece of UI defined as a JavaScript function (or class) that returns JSX. Think of it like a Lego block — you build a page by composing many small components (Button, Card, NavBar). Each owns its own logic and styling, which makes the UI easier to maintain and test.

Question

What is JSX?

Answer

JSX is a syntax extension that lets you write HTML-like markup directly inside JavaScript. Under the hood it compiles to React.createElement() calls. So <div>Hi</div> becomes React.createElement('div', null, 'Hi') — JSX is just sugar that makes UI code feel natural to read.

Question

Props vs State?

Answer

Props are inputs a component receives from its parent — they're read-only, like function arguments. State is data the component owns and can change over time, and changing it triggers a re-render. Rule of thumb: if a value can change while the component is alive, it's state; if it's given from outside, it's props.

Question

Functional vs Class components?

Answer

Functional components are plain JavaScript functions that return JSX and use hooks for state and side effects. Class components use ES6 classes with lifecycle methods like componentDidMount. Modern React strongly prefers functional + hooks — shorter code, easier reuse, and React's new features mostly target this style.

Question

What are the React lifecycle phases?

Answer

Three phases: Mounting (component is created and inserted into the DOM), Updating (props or state change cause a re-render), and Unmounting (component is removed). With hooks, useEffect handles all three phases via its dependency array and its returned cleanup function.

Question

What does useState return?

Answer

It returns an array with two items: the current state value and a setter function to update it. You usually destructure: const [count, setCount] = useState(0). Calling the setter schedules a re-render with the new value — React batches multiple setter calls in the same event into a single render.

Question

What does useEffect do?

Answer

useEffect runs side effects after the component renders — things like fetching data, setting up subscriptions, or touching the DOM. The dependency array decides when it re-runs: empty [] means once on mount, [x] means whenever x changes, and no array means after every render.

Question

When does useEffect cleanup run?

Answer

The function you return from useEffect runs before the next effect fires and when the component unmounts. Use it to undo what the effect did — unsubscribe from a socket, clear a timer, abort a fetch. Without cleanup, you'll leak memory and trigger 'setState on unmounted component' warnings.

Question

What is useMemo for?

Answer

useMemo caches the result of an expensive calculation so it isn't recomputed on every render. You give it a function and a dependency array — it only re-runs the function when deps change. Use it for genuinely heavy work (sorting big arrays, deriving complex objects), not as a blanket optimization.

Question

What is useCallback for?

Answer

useCallback returns a memoized version of a function whose reference stays stable across renders. It's useful when you pass callbacks to memoized child components (React.memo) — without it, a new function reference each render busts the child's memoization and causes re-renders.

Question

What is useRef used for?

Answer

useRef holds a mutable value that persists across renders but does NOT trigger a re-render when changed. Two main uses: accessing DOM nodes (ref={inputRef}, then inputRef.current.focus()) and storing values like timers, previous props, or any 'box' you want without state semantics.

Question

What is useReducer for?

Answer

useReducer manages state via a reducer function: (state, action) => newState. You dispatch actions like {type: 'increment'} and the reducer returns the next state. It shines when state has multiple related fields or many transitions, where useState would spawn a tangle of setters.

Question

When should you prefer useReducer over useState?

Answer

Use useReducer when state logic is complex, has many sub-values that change together, or the next state depends heavily on the previous one. Also handy when several components need to dispatch the same actions, or when you want to keep state-update logic outside the component for testing.

Question

What is a custom hook?

Answer

A custom hook is a regular function whose name starts with 'use' and that calls other hooks inside. It lets you extract and share stateful logic across components — e.g. useAuth, useDebounce, useLocalStorage. Each component that calls it gets its own isolated state, but the logic stays in one place.

Question

What are the rules of hooks?

Answer

Two rules: only call hooks at the top level (never inside conditions, loops, or nested functions), and only call them from React function components or other custom hooks. React relies on the call order being identical between renders to match each hook call with its stored state.

Question

What is reconciliation?

Answer

Reconciliation is React's process of comparing the new virtual DOM tree to the previous one and figuring out the minimum set of changes needed in the real DOM. Instead of re-rendering everything, React diffs the trees and applies just the diff — which is what makes it fast despite re-running render functions.

Question

What is the diffing algorithm?

Answer

React's diff is a heuristic that runs in O(n): if element types differ, the whole subtree is replaced; if they match, only props are updated; and lists use keys to identify which items moved, were added, or removed. A naive tree diff would be O(n³) — React trades exactness for speed.

Question

What is React Fiber?

Answer

Fiber is React's reconciliation engine (since v16). It splits rendering work into small units called 'fibers' that React can pause, resume, and prioritize. This is what enables concurrent features like time-slicing, Suspense, and transitions — keeping the UI responsive even during heavy renders.

Question

Render vs Commit vs Paint?

Answer

Render: React calls your function components to figure out what the new tree should look like. Commit: React applies the diff to the real DOM and runs refs/lifecycle effects. Paint: the browser then draws pixels on screen. Render and commit are React's work; paint is the browser's.

Question

What is the Virtual DOM?

Answer

The Virtual DOM is an in-memory JavaScript representation of the UI tree. When state changes, React builds a new virtual tree, diffs it against the old one, and only applies the differences to the real DOM. Touching the real DOM is expensive, so this batching makes updates much cheaper.

Question

What is automatic batching?

Answer

React 18 groups multiple state updates that happen in the same event into a single re-render — even across async boundaries like promises, timeouts, and native event handlers. Before, only updates inside React event handlers were batched, so an update inside setTimeout would cause an extra render.

Question

What is concurrent rendering?

Answer

Concurrent rendering is React 18's ability to prepare multiple versions of the UI at the same time and interrupt long renders so urgent updates (like typing) aren't blocked. It powers features like useTransition and Suspense, giving users a snappier experience under heavy work.

Question

What is Suspense?

Answer

Suspense is a component that lets you declaratively show a fallback (like a spinner) while its children are still loading — either code (React.lazy) or data (with frameworks that support it). It pushes loading-state handling up the tree, so each child doesn't need its own 'isLoading' boilerplate.

Question

What is React.lazy?

Answer

React.lazy lets you code-split a component so its JavaScript is downloaded only when it first renders, not on initial page load. You wrap the lazy component in a Suspense boundary to show a fallback while the chunk loads. Great for big routes, modals, or charts that most users won't see immediately.

Question

What is an error boundary?

Answer

An error boundary is a special class component (using componentDidCatch / getDerivedStateFromError) that catches JavaScript errors in its child component tree and renders a fallback UI instead of crashing the whole app. They don't catch errors in event handlers, async code, or themselves — just rendering errors below.

Question

Controlled vs uncontrolled components?

Answer

In a controlled input, React state holds the value and onChange updates it — the DOM mirrors React. In an uncontrolled input, the DOM owns the value and you read it via a ref when needed. Controlled is the default in React; uncontrolled is useful for simple forms or wrapping non-React libraries.

Question

What is the Context API?

Answer

Context lets you pass data through the component tree without manually threading props through every level (prop drilling). You create a Context, wrap part of the tree in <Context.Provider value={...}>, and any descendant can read it with useContext. Good for theme, auth user, language — values that rarely change.

Question

When should you NOT use Context?

Answer

Avoid Context for values that change frequently and affect a large subtree, because every consumer re-renders when the value changes. For state with frequent updates or many consumers, libraries like Zustand or Redux let components subscribe to just the slice they need, avoiding wasteful re-renders.

Question

What is React.memo?

Answer

React.memo is a higher-order component that memoizes a functional component — it skips re-rendering when the new props are shallow-equal to the previous ones. Wrap a component with it when its parent re-renders often but its own props rarely change. Stabilize prop references (useMemo/useCallback) or it won't help.

Question

Why doesn't React.memo always prevent re-renders?

Answer

Because shallow equality compares references, not deep values. If a parent passes a new object/array/function literal each render (like style={{color:'red'}} or onClick={() => …}), the memoized child sees a 'new' prop and re-renders anyway. Fix it by stabilizing those props with useMemo/useCallback.

Question

What is memoization in React?

Answer

Memoization is caching a computed value (or component output) so it's reused when its inputs haven't changed. React exposes three tools: useMemo for values, useCallback for function references, and React.memo for components. The idea is the same as caching — trade memory for speed.

Question

Common causes of unnecessary re-renders?

Answer

Parent re-rendering when nothing meaningful changed, new object/function references in props, Context value changing too often, unstable keys in lists, or inline objects/arrays in JSX. Use the React DevTools Profiler to see which components are re-rendering and why — guesswork rarely lands on the real culprit.

Question

What is code splitting?

Answer

Code splitting breaks your JavaScript bundle into smaller chunks that load on demand rather than all upfront. Typical splits: per route, per heavy feature (charts, editors), and per third-party library. The result is a smaller initial download and faster first paint — critical for mobile and slow networks.

Question

How do you bundle-optimize a React app?

Answer

Code splitting by route, tree shaking unused exports, dynamic imports for heavy widgets, lazy-loading images, dropping unused dependencies, and analyzing the bundle with webpack-bundle-analyzer or rollup-plugin-visualizer. Small wins compound — a slim bundle is the single biggest perf lever on the web.

Question

What is list virtualization?

Answer

Virtualization renders only the items currently visible in a long list (plus a small buffer above/below), reusing DOM nodes as the user scrolls. Libraries like react-window or @tanstack/react-virtual make 100k-row tables feel instant. Without it, the browser chokes on tens of thousands of DOM nodes.

Question

What's a recommended folder structure for a large React app?

Answer

Feature-based: each feature (auth, dashboard, billing) owns its components, hooks, API calls, and tests in one folder. Shared things go in 'common', 'ui', or 'lib'. The goal is co-location — a feature can be understood (and deleted) without hunting through ten distant directories.

Question

What makes a frontend scalable?

Answer

Clear feature boundaries, separation of UI from business logic, typed contracts (TypeScript) between layers, a coherent state-management strategy, lazy loading at route level, and consistent patterns enforced by linting. Scale isn't about one perfect tool — it's about predictability so new contributors aren't lost.

Question

What is API caching on the frontend?

Answer

Storing API responses (in memory or persistent storage) so repeated requests reuse data instead of refetching. Libraries like TanStack Query, RTK Query, and SWR handle this for you: dedupe in-flight requests, serve cached data instantly, then refetch in the background. Huge win for UX and server load.

Question

What does a typical SPA authentication flow look like?

Answer

User submits credentials → server validates and returns a token (JWT) or sets a session cookie → client stores it (HTTP-only cookie is safest) → the token is sent on every API call → if it expires, a refresh token gets a new one. Logout clears the token. Always validate auth on the server, not just the UI.

Question

How do you protect routes in a React app?

Answer

Wrap private routes in an auth-checking component (e.g. <RequireAuth>) that reads the current user from your auth store; if no user, it redirects to /login. In React Router v6, this is usually done with a layout route or a loader. The server must still enforce authorization on API calls.

Question

What is role-based access control on the frontend?

Answer

Showing or hiding UI based on the user's role — admins see admin menus, viewers don't see the delete button. It's purely UX polish; the real enforcement must happen server-side, because anyone can edit client code. Use a single helper (hasRole('admin')) to keep checks consistent.

Question

What is Redux Toolkit?

Answer

Redux Toolkit is the official, opinionated Redux library that eliminates most of classic Redux's boilerplate. It gives you configureStore, createSlice (reducers + actions in one), createAsyncThunk for async logic, and built-in Immer so you can 'mutate' state safely. New Redux code should always use RTK.

Question

What is a Redux slice?

Answer

A slice is a bundle of state, reducers, and auto-generated action creators for one feature, created with createSlice. It replaces the old pattern of writing separate action constants, action creators, and reducer switch statements. One file, one feature — much less ceremony.

Question

What is Zustand?

Answer

Zustand is a minimal state-management library that uses hooks directly. You create a store with a function, then call useStore() in any component to read/update state. No providers, no boilerplate, tiny bundle. Great when Redux feels heavyweight but useState/Context aren't enough.

Question

Redux vs Zustand — when to pick which?

Answer

Redux (Toolkit): more structure, devtools, middleware ecosystem, better for very large teams and complex async logic. Zustand: lightweight, much less code, easier for small-to-medium apps and prototypes. Both work fine in production — pick based on team size, complexity, and personal taste.

Question

What is RTK Query?

Answer

RTK Query is Redux Toolkit's built-in data-fetching solution. You define endpoints once and get auto-generated hooks like useGetUsersQuery — with caching, deduplication, polling, refetching, and invalidation handled for you. Think 'TanStack Query but tightly integrated with Redux'.

Question

What is TanStack Query (React Query)?

Answer

TanStack Query is a library for managing server state: caching, background refetching, optimistic updates, pagination, and stale-while-revalidate — all decoupled from your global store. You write a queryFn, give it a key, and it handles the rest. It's become the default for data fetching in modern React.

Question

Server state vs client state?

Answer

Server state is data that lives on a backend and is cached locally — it's async, can go stale, and needs refetching (queries). Client state is data that lives only in the browser — UI toggles, form drafts, theme. They have different needs, so manage them with different tools.

Question

What's a typical dashboard architecture?

Answer

Lazy-loaded widget components that fetch in parallel via TanStack Query, a layout grid the user can rearrange, server-side filtering (push work off the client), real-time updates over WebSocket or polling, and role-based widget visibility. Cache aggressively, render skeletons, and avoid blocking the whole page on one slow widget.

Question

What's the frontend architecture for a chat app?

Answer

A WebSocket layer that pushes messages, a message store keyed by conversation, a virtualized list (chats can have 10k+ messages), optimistic sends (show the message instantly, mark failed on error), retry logic for reconnects, presence/typing indicators, and infinite-scroll loading for history.

Question

How do you implement real-time updates in a frontend?

Answer

Three main options: WebSockets (full-duplex, lowest latency, best for chat/games), Server-Sent Events (one-way push from server, simpler), and polling (good enough for slow-changing data). On reconnect, refetch the latest snapshot so the user doesn't see stale state.

Question

What is an optimistic update?

Answer

An optimistic update changes the UI immediately as if the server request had already succeeded — like a sent message appearing instantly in chat. If the request later fails, you roll back the change and show an error. Makes the app feel instant even on slow networks.

Question

What is hydration in React?

Answer

Hydration is React attaching event listeners and state to HTML that was server-rendered, so the static markup becomes interactive. It's why SSR can feel instant — the user sees the page right away, and JS hooks it up after. A mismatch between server HTML and client output triggers a hydration warning.

Question

Why use keys in lists?

Answer

Keys help React identify which items changed, moved, were added, or removed across renders. Without stable keys, React can't tell items apart and may rebuild DOM nodes unnecessarily, losing focus and animation state. Use a stable unique ID — array indices break when the order changes or items are inserted.

Question

What is prop drilling?

Answer

Prop drilling is passing a prop through many intermediate components that don't actually use it, just so a deep child can receive it. It clutters component signatures and couples unrelated layers. Fix it with Context (for low-frequency data), Zustand/Redux (for shared state), or component composition (children pattern).

Question

What are render props?

Answer

Render props is a pattern where a component takes a function as a child or prop and calls it to render content, passing some data along. It was popular for sharing logic before hooks (e.g. <Mouse>{({x,y}) => <Cat at={x,y} />}</Mouse>). Hooks have largely replaced it for new code.

Question

What are higher-order components (HOCs)?

Answer

An HOC is a function that takes a component and returns a new component with extra behavior — like withRouter or connect from old Redux. They were the way to share logic pre-hooks. They still work, but custom hooks are simpler, more readable, and cause fewer wrapper-tree headaches.

Question

What are synthetic events in React?

Answer

React wraps native browser events in a SyntheticEvent that smooths out cross-browser differences and provides a consistent API. It looks and behaves like a native event (e.preventDefault, e.target) but is reusable across all browsers. Since React 17, event pooling is gone, so you can use the event asynchronously safely.

Question

What is React StrictMode?

Answer

StrictMode is a development-only wrapper that intentionally double-invokes certain functions (rendering, effects) to surface bugs like impure renders or missing cleanups. It also warns about deprecated APIs. It has zero effect in production — purely a tool to catch problems early during development.

Question

Why does useEffect run twice in development?

Answer

Because StrictMode mounts your component, unmounts it, and remounts it during development to verify that your cleanup function is correct. If your effect leaks state (e.g. doesn't cancel a subscription), the double-mount surfaces the bug immediately. In production, the effect runs once as expected.

Question

What is useLayoutEffect?

Answer

Like useEffect, but it fires synchronously after DOM mutations and BEFORE the browser paints. Use it only when you need to measure or mutate the DOM and avoid a visible flash (e.g. positioning a tooltip). Otherwise stick to useEffect — useLayoutEffect blocks paint and hurts performance.

Question

What is useTransition?

Answer

useTransition marks a state update as non-urgent ('a transition'), letting React keep the UI responsive while it works on the slower update in the background. Classic example: filtering a huge list as the user types — the input stays snappy because typing is urgent and re-filtering is a transition.

Question

What is useDeferredValue?

Answer

useDeferredValue returns a deferred copy of a value that lags behind during heavy renders. Pass it to expensive children so they render with the older value while the latest one is still being processed. Pairs well with Suspense for smooth-feeling search/filter UIs.

Question

What is useId?

Answer

useId generates a unique, stable ID that's consistent between server and client renders. It's perfect for accessibility — connecting <label htmlFor> to <input id> — when you don't have a natural id to use. Don't use it for keys in lists; it's for ids that need to match across SSR.

Question

What does React.forwardRef do?

Answer

forwardRef lets a component pass a ref it receives through to a child DOM node or another component. Without it, refs only attach to native elements, so a parent can't focus your <CustomInput>. Wrap with forwardRef and you can. Used heavily by component libraries.

Question

What is useImperativeHandle?

Answer

useImperativeHandle lets you customize what a parent gets when it uses a ref on your component. Instead of exposing the raw DOM node, you expose specific methods like { focus(), open(), reset() }. Use sparingly — refs are an escape hatch, and prop-driven APIs are usually cleaner.

Question

What are React portals?

Answer

ReactDOM.createPortal renders children into a DOM node OUTSIDE the current parent — typically appended to document.body. Perfect for modals, tooltips, and dropdowns that need to break out of the parent's overflow:hidden or z-index stacking context, while still receiving events via the React tree.

Question

What is a Fragment in React?

Answer

<></> or <Fragment> lets a component return multiple children without wrapping them in an extra DOM element. Useful for table rows, list items, or any place where adding a <div> would break layout. The key prop works on Fragment for lists.

Question

Why is stable identity important?

Answer

Memoized components and effects use referential equality to decide whether to re-run. If you create a new object/function literal each render, the reference changes and memoization breaks. Stable identities (via useMemo/useCallback or moving values out of render) let React skip work safely.

Question

What is the children prop?

Answer

children is a special prop containing whatever JSX is nested between a component's opening and closing tags. It enables composition: <Card><Header/><Body/></Card>. Inside Card you render {children}. This pattern is more flexible than passing components via named props.

Question

What's composition over inheritance in React?

Answer

Instead of extending base components (class inheritance), you build features by composing small components and passing children, render props, or function props. e.g. a Modal accepts children rather than being subclassed. Composition keeps APIs flexible and avoids deep, brittle inheritance chains.

Question

How do you debounce input in React?

Answer

Wrap your handler with a debounced version (e.g. lodash.debounce) inside useMemo or useCallback so it survives re-renders, or write a custom useDebouncedValue hook. Always clear the timer on unmount to avoid leaks. Debouncing is essential for search-as-you-type to avoid spamming the server.

Question

How do you throttle scroll events in React?

Answer

Use lodash.throttle, requestAnimationFrame, or a useThrottle hook to limit the handler to once per N milliseconds. Add the listener in useEffect and clean it up on unmount. Without throttling, scroll fires dozens of times per second and can tank perf.

Question

What are React Server Components?

Answer

Server Components run only on the server, fetch data directly, and send a serialized output to the client — they never ship their JS to the browser. They can't use useState/useEffect (no interactivity) but can drastically reduce bundle size. Client components live alongside them for interactive bits.

Question

Client vs Server Component?

Answer

Client components run in the browser, can use state, effects, and event handlers — marked with 'use client'. Server components run on the server, can fetch data and access secrets, can't use hooks. You mix both: server for static/data, client for interactive islands.

Question

What is a hydration mismatch?

Answer

A hydration mismatch happens when the HTML rendered on the server differs from what the client renders on first render. React warns because it can't safely attach event handlers. Common causes: rendering Date.now(), random values, or browser-only state during SSR. Fix by deferring those to useEffect.

Question

How do you handle forms in React?

Answer

For simple forms: a few controlled inputs with useState. For larger forms: react-hook-form (uncontrolled, very fast, minimal re-renders) or Formik. Pair with a schema validator like Zod or Yup so the same rules drive client and server validation.

Question

What is React Router?

Answer

React Router is the de-facto routing library for React. It maps URLs to components, supports nested layouts, dynamic params, and (in v6.4+) data loaders that fetch in parallel with code. Most React apps use it unless they're on a framework like Next.js that has its own router.

Question

What's a route loader?

Answer

A loader is a function tied to a route that fetches data before the route renders. It runs in parallel with code-splitting, avoiding the 'waterfall' where a component mounts, then triggers a fetch, then waits. React Router v6.4+ and Remix both use this pattern.

Question

What's a cache key in TanStack Query?

Answer

An array (e.g. ['user', userId]) that uniquely identifies the query. Two components calling useQuery with the same key share the same cache entry and won't double-fetch. Changing any value in the key triggers a refetch. Treat keys like dependency arrays — include everything that affects the response.

Question

How does TanStack Query handle stale data?

Answer

It returns cached data instantly, then refetches in the background if the data is older than staleTime. Once fresh data arrives, all subscribed components re-render. This 'stale-while-revalidate' pattern gives users instant UI plus eventual freshness without writing manual cache logic.

Question

How do you invalidate cached queries?

Answer

Call queryClient.invalidateQueries({ queryKey: ['users'] }) — usually after a mutation succeeds. It marks matching queries stale and triggers refetches. You can also imperatively setQueryData for instant updates without a round trip — useful for optimistic patterns.

Question

What are uncontrolled forms good for?

Answer

When you have lots of fields and don't need to react on every keystroke. Values stay in the DOM, no re-render per character. react-hook-form uses this model and benchmarks dramatically faster than fully-controlled forms for large UIs like checkout or settings pages.

Question

What does ReactDOM.render do?

Answer

It mounts a React element tree into a real DOM container — the entry point of your app. In React 18+, it's deprecated in favor of createRoot(container).render(element), which opts you into concurrent features like automatic batching and Suspense for data fetching.

Question

What does createRoot enable?

Answer

createRoot opts your app into React 18's concurrent rendering. That unlocks automatic batching of all updates, useTransition, useDeferredValue, and Suspense for data fetching. Old apps using ReactDOM.render keep the legacy behavior until they migrate.

Question

What is Hot Module Replacement (HMR)?

Answer

HMR is a dev-server feature that swaps changed modules into a running app without a full page reload, preserving local state. Save a file, see the change instantly with your form still filled in. Vite and webpack-dev-server both support it; it's a huge productivity boost.

Question

How do you handle errors in async code in components?

Answer

Wrap async logic in try/catch, store the error in state, and render it conditionally. Or use TanStack Query, which exposes { error, isError } for free. For unexpected errors, wrap the tree in an error boundary so a crash doesn't take down the whole app.

Question

How do you test a React component?

Answer

Use React Testing Library to render the component, query by accessible roles/text (not internal classnames), simulate user actions with userEvent, and assert visible behavior. Test what the user sees — not implementation details. Tests stay green through refactors that don't change behavior.

Question

What is shallow rendering?

Answer

Shallow rendering renders a component without rendering its children — Enzyme popularized it. Modern guidance discourages it: testing isolated components misses integration bugs, and React Testing Library prefers full integration-style renders that exercise actual behavior.

Question

What equality does React use to bail out of a setState?

Answer

Object.is. If the value you pass to a state setter is Object.is-equal to the current value, React skips the re-render entirely. This is why setState(state) (passing the same object) is a no-op, and why you must create new references when state changes.

Question

What's a common gotcha with useEffect dependencies?

Answer

Missing a dependency causes stale closures (your effect uses an old value). Including object/array literals causes infinite loops (new reference each render). Fix with the eslint-plugin-react-hooks rule, useMemo/useCallback for object deps, or refs for values you read but don't 'depend on'.

Question

What is a stale closure?

Answer

A stale closure happens when a callback captures an old value from a previous render because it wasn't included in deps. Example: an interval reading 'count' set up once will always see count=0. Fix by adding count to deps (and recreating the interval) or by using a ref that holds the latest value.

Question

How do you share logic between two components?

Answer

Extract it into a custom hook for stateful logic, or a plain utility function for pure logic. Hooks are the modern standard; they're easier to read, type, and test than HOCs or render props. Each component using the hook gets its own state — like calling useState.

Question

What happens in React's commit phase?

Answer

After rendering, React applies DOM mutations, then runs refs, then synchronous layout effects (useLayoutEffect). The browser paints. Then passive effects (useEffect) run asynchronously. So if you read DOM measurements, do it in useLayoutEffect; for non-visual side effects, useEffect is better.

Question

Effect vs layout effect ordering?

Answer

useLayoutEffect runs synchronously after DOM mutations but BEFORE the browser paints — blocks paint. useEffect runs after paint, asynchronously. Use useLayoutEffect only when you must avoid a visual flash (e.g. measuring then repositioning); otherwise useEffect is the better default.

Question

What's batching across async boundaries?

Answer

Since React 18, updates inside promises, setTimeout, native event handlers, etc., are batched into a single render. Before 18, only updates inside React event handlers were batched — code inside fetch().then() caused two separate renders for two setState calls. Now they're combined automatically.

Question

What is flushSync?

Answer

flushSync forces React to commit a state update synchronously, opting out of batching. Use it only when you need DOM to update before some imperative code runs — like measuring after a setState. It can hurt performance, so reach for it sparingly.

Question

What does StrictMode help catch?

Answer

Side effects in render (e.g. mutating a parent's data), unsafe legacy lifecycles, deprecated APIs, and incorrect effect cleanups (it double-invokes effects and mount/unmount/remount to expose missing cleanup). It's free safety — keep it on in development for new projects.

Question

Why are inline arrow functions in JSX sometimes a problem?

Answer

Each render creates a new function reference. If you pass it to a React.memo'd child or as a dependency, you'll break memoization and cause unnecessary re-renders. For leaf elements that aren't memoized, it's totally fine — don't optimize prematurely.

Question

What is tree shaking?

Answer

Tree shaking is dead-code elimination during bundling: the bundler keeps only the exports you actually import and drops the rest. ES modules' static import/export syntax is what makes this possible. Use named imports rather than namespace imports to give the bundler the most info.

Question

How do you detect re-renders in React?

Answer

Use React DevTools Profiler to record a session and see which components rendered, how often, and why. The 'why-did-you-render' library logs noisy re-renders to the console. console.log inside the component body also works for quick checks but doesn't tell you the reason.

Question

What does Suspense for data fetching do?

Answer

Components 'throw a promise' while their data is loading; the nearest Suspense boundary catches it and shows fallback UI until the promise resolves. Frameworks (Next.js, Remix, Relay) integrate this so you write components as if data were synchronous, and Suspense handles the loading state declaratively.

Question

What's the WebSocket lifecycle inside a React component?

Answer

Open the socket in useEffect on mount, attach 'message'/'open'/'close' handlers, store the socket in a ref. In cleanup, remove handlers and call socket.close(). Without proper cleanup you'll have phantom connections in dev (thanks to StrictMode) and leak memory in production on route changes.

Practise React & Frontend in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: JavaScript & TypeScript Backend Engineering Databases System Design AI & Agentic AI DevOps & Cloud Security Testing DSA Coding Problems (Python)