Season 1 revision

Namaste Reactthe night-before notebook

Nine episodes from your notes, a crash course on episodes 10 to 13, the extra depth an SDE-2 panel expects, plus chapters on frontend security, JavaScript polyfills, frontend theory and an HTML & CSS brush-up. Every page ends with interview cards: tap a question, answer it out loud, then check yourself.

★Pick a page

★If you only have 10 minutes

say these out loud
  1. JSX → Babel → React.createElement / jsx() → plain object → ReactDOM commits to the real DOM.
  2. State change → component function re-runs → new virtual tree → reconciliation (diff) → minimal DOM commit.
  3. Keys tell the diff which list item is which. Stable IDs, never Math.random() during render, index only for static lists.
  4. Render phase is pure and can be paused (Fiber). Commit phase touches the DOM and runs effects/lifecycles.
  5. useEffect runs after paint. [] = after mount, [x] = when x changes, none = after every render. Return a cleanup.
  6. State is a snapshot per render; updates are batched. Use setX(prev => ...) when the next value depends on the old one.
  7. Rules of hooks: top level only, only in components or custom hooks, because React matches hooks by call order.
  8. Client-side routing swaps components without a document request; Link not <a>; Outlet renders child routes.
  9. Class lifecycle: constructor → render → commit → componentDidMount; update → render → componentDidUpdate; componentWillUnmount for cleanup.
  10. Optimize: custom hooks for logic reuse, lazy() + Suspense for code splitting, memoize only measured hot spots.

Built from your Episode 1–9 notes. Course: Namaste React by Akshay Saini. Code reference: github.com/chetannada/Namaste-React. Where your notes were imprecise, look for the green “Fix in your notes” strips.

Episode-01

Inception

In one breath: React is just JavaScript. React.createElement makes a plain object describing UI, and ReactDOM turns that object into real DOM inside one root node.

★The three APIs

React.createElement(type, props, ...children)

type: tag string like "h1" or a component.
props: attributes object (or null).
children: text, elements, or an array.

Returns a React element, an object. Not a DOM node.

ReactDOM.createRoot(domNode)

Tells React “you own everything inside this node”. Returns a root with two methods: render and unmount.

root.render(reactNode)

Converts the element tree into DOM and puts it in the root. Existing children of #root get replaced. Returns undefined.

createElement ("h1", {id:"title"}, "Namaste") React element { $$typeof: Symbol, type: "h1", props: {id, children}, key: null, ref: null } root .render() Real DOM <div id="root"> <h1 id="title"> Namaste</h1> you describe just a JS object, cheap to create browser paints this
React elements are descriptions; ReactDOM is the renderer that makes them real.

★Things the notes taught

  • React is an island. Divs above and below #root stay untouched, so React can be added to one part of an existing page.
  • Script order matters. Your script must run after the React and ReactDOM scripts, otherwise React is not defined.
  • “Not rendered yet” placeholder inside root makes it obvious when React failed to mount.
  • Props are passed to DOM as attributes: className (not class), style as an object. Unknown lowercase props like hello: "world" also land as attributes.
  • Multiple children go in an array, and arrays need key on each child.
Interview gotcha
Style keys inside createElement should be camelCase: backgroundColor. The notes wrote "background-color"; React warns about hyphenated style keys (CSS custom properties like --x are the exception).
Fix in your notes: React 19 removed the UMD builds, so the unpkg.com/react@18/umd script pattern only works for React 18. Today you would use a bundler or an ESM CDN. Also, ReactDOM.render (pre-18 API) was removed in React 19; createRoot from react-dom/client is the only client root API.

★Interview cards

Episode-02

Igniting our App

In one breath: React alone doesn't make an app fast. npm manages packages, and a bundler (Parcel) gives us a dev server, HMR, minification, tree shaking and code splitting.

★npm and the files it creates

File / folderWhat it isCommit to git?
package.jsonProject config + dependency ranges (^2.8.2)Yes
package-lock.jsonExact installed versions + integrity hash of every package (incl. transitive)Yes, always
node_modules/The actual code. Heaviest folder, regenerated with npm installNo
dist/Parcel's build output (dev or production)No
.parcel-cache/Parcel's cache so rebuilds are fastNo

Rule of thumb: anything that can be regenerated goes in .gitignore.

2.8.2 2.9.0 3.0.0 ^2.8.2 caret: minor + patch updates, < 3.0.0 ~2.8.2 tilde: patch only, < 2.9.0 exact "2.8.2" = pinned
Semver is MAJOR.MINOR.PATCH. The lock file pins the exact version actually installed.
dependencies
Needed when the app runs: react, react-dom, react-router-dom. npm i react
devDependencies
Needed only to build/test: parcel, jest, babel plugins. npm i -D parcel

npm vs npx: npm installs and runs scripts; npx parcel index.html executes a package binary without a global install.

★What Parcel does for us

your src index.html App.js styles.css images Parcel (zero-config bundler) 👀 File watcher (C++) → HMR 🗄 Caching in .parcel-cache 🔁 Babel transpile (JSX, old browsers) 📦 Bundling + code splitting 🗜 Minify + compress + content hashing 🌳 Tree shaking (drop unused exports) 🖼 Image optimization, dev HTTPS, port 🧯 Friendly error overlay / diagnostics npx parcel index.html dev server :1234 HMR, source maps, fast npx parcel build index.html dist/ optimized index.[hash].js
Dev build is optimized for speed of iteration; production build is optimized for the user's download.
HMR

Hot Module Replacement swaps changed modules in the running page, often keeping state. Parcel's file watcher notices the change, cache keeps rebuilds in milliseconds.

Tree shaking

Removes exports you never import. Works because ES module import/export are static and analyzable at build time (CommonJS require is not).

browserslist

"browserslist": ["last 2 versions"] in package.json tells Babel/Parcel which browsers to support, so it knows how much to transpile and polyfill.

★Errors you met (and why)

  • Browser scripts cannot have imports or exports → add type="module" to the script tag loading App.js.
  • You are importing createRoot from "react-dom" → import from "react-dom/client".
  • Build fails because "main": "App.js" conflicts with an HTML entry → delete main from package.json.

Transitive dependencies: your packages depend on other packages, forming a dependency tree. The lock file pins all of them.

Fix in your notes: the tilde line reads "^2.8.2" twice; it should be "~2.8.2" → 2.8.2 up to < 2.9.0. And it's “zero config”, not “xero”. The “consistent hashing” point is better described as content hashing of output file names (index.cbf957bf.js) for long-term browser caching.
SDE-2 context
Create React App was officially deprecated by the React team in early 2025. In interviews, know the landscape: Vite (native-ESM dev server, fast), Webpack (most configurable, legacy-heavy), Parcel (zero config), and frameworks like Next.js or React Router (framework mode) that ship their own build.

★Interview cards

Episode-03

Laying the Foundation

In one breath: JSX is HTML-like syntax that Babel compiles into createElement calls. A functional component is just a function that returns JSX.

★npm scripts

★The JSX journey

JSX <h1 className="t"> Hi</h1> Babel via Parcel compiled JS React.createElement( "h1",{className:"t"},"Hi") or _jsx("h1", {...}) in React 17+ object React element DOM ReactDOM Browsers can't read JSX. It must be compiled before it ever reaches the JS engine.
JSX is not HTML
  • className, htmlFor, camelCase events (onClick)
  • Every tag must close: <img />
  • { } embeds a JS expression (not a statement)
  • JSX is separate from React; React just uses it
Babel

A JS compiler/transpiler: JSX → JS, and modern syntax → older syntax per browserslist. Missing APIs get polyfills (e.g. core-js) — replacement implementations of features old browsers lack.

Safety (sanitization)

Values inside { } are escaped before insertion, so {userInput} can't inject a script. The escape hatch dangerouslySetInnerHTML is named that way on purpose.

★Functional components

Component composition = building a component out of other components. That's the whole React mental model: small pieces, nested.

Interview gotcha: <Title /> vs {Title()}
<Title /> creates an element; React calls the function, gives it its own spot in the tree, its own state and hooks. {Title()} just runs the function inline: its hooks become the parent's hooks, and React can't bail out of rendering it separately. Use the tag.
Fix in your notes: capitalizing a component name is required, not just good practice. In JSX, lowercase <title /> compiles to the string "title" (an HTML tag); capitalized <Title /> compiles to a reference to your function. Also, since React 17's automatic JSX runtime, you don't need import React just to write JSX.
Fix in your notes: Parcel does not strip console.log by default (your notes caught this). Use babel-plugin-transform-remove-console in .babelrc, with {"exclude": ["error","warn"]} to keep errors and warnings.

★Interview cards

Episode-04

Talk is Cheap, Show me the Code

In one breath: We start Food Villa. Props pass data down, map() renders lists, keys let React's diffing algorithm match old and new items, and Fiber is the engine doing that work.

★The app we're building

AppLayout Header Body Footer Logo NavItems Cart SearchBar RestaurantList → Card ×N Links Copyright image, name, rating, cuisines via props

★Fragments and one parent

A component returns one JSX expression because JSX compiles to one createElement call, and a function can only return one value. Wrapping in a <div> adds a useless DOM node; a fragment doesn't.

★Styling in JSX

Inline style
style={{ backgroundColor: "red" }}
Outer braces = JS, inner braces = object. camelCase keys, commas not semicolons.
External CSS
className="card" + rules in a .css file. Preferred for anything non-trivial (later: Tailwind, CSS modules).

★Props

Props are arguments to a component. React collects all attributes into one object and passes it as the first parameter. They flow parent → child only and are read-only inside the child.

Optional chaining res?.info?.name returns undefined instead of throwing when something in the chain is null/undefined. Essential with API data.

Config-driven UI: the backend sends data describing what to show (which carousels, offers, layout per city) and the UI renders whatever the config says. Swiggy's home page works this way.

★Virtual DOM, diffing and keys

old virtual tree new virtual tree real DOM diff Reconciliation: compare trees, then commit only the changed node (pink) to the real DOM.
Diffing heuristics (O(n))
  • Different element type → throw away subtree, build new.
  • Same type → keep node, update changed attributes.
  • Lists → match children by key.

Generic tree diff is O(n³); these two assumptions make it O(n).

Key choices
  • ✓ Stable unique ID from data (res.info.id)
  • ~ Index: only for static lists that never reorder/filter
  • ✗ Math.random() / shortid.generate() inside render
key = index 0: A1: B 0: Z1: A2: B every row “changed”;input state sticks tothe wrong row key = id a: Ab: B z: Za: Ab: B only Z inserted,A and B reused
Insert “Z” at the top. Index keys make React think every row changed.
Fix in your notes: key={shortid.generate()} inside map creates a new key every render, so React unmounts and remounts every card each time (lost state, wasted work). Generate IDs once when data arrives, or use the API's ID.
React Fiber (React 16+)

A rewrite of the reconciler. Each component instance becomes a fiber node, a unit of work. Rendering can be split into chunks, paused, prioritized, resumed or thrown away, while the commit stays synchronous. React keeps two trees (current and work-in-progress) and swaps them on commit. This is what makes concurrent features (transitions, Suspense) possible.

★Interview cards

Episode-05

Let's get Hooked!

In one breath: Split code into files, export/import components, and use useState so React knows when data changed and re-renders the UI.

★Folder structure

★Default vs named exports

DefaultNamed
Exportexport default Header;export const LOGO_URL = "...";
Importimport Header from "./Header";import { LOGO_URL } from "./constants";
Per fileOnly oneMany
Rename on importAny name works{ LOGO_URL as logo }
Both togetherimport Header, { Title } from "./Header"; (default first)

import * as Obj from "./Title" gives a namespace object for all named exports. export default { Title, Header } exports one object, which is why <Obj.Header/> works there.

★Why a normal variable doesn't work

A plain let searchText changes in memory, but React has no idea, so nothing re-renders, and the next render resets it anyway. A state variable lives in React (on the component's fiber), survives renders, and its setter schedules a re-render.

User types “Ka” onChange(e) setSearchText("Ka") queues an update, no instant change Body() runs again searchText === "Ka" this render Reconciliation diff new vs old virtual tree Commit to DOM only changed nodes one-way data flow: state → UI value + onChange = “two-way binding” by hand
The search bug, explained properly
Searching “K” then “o” gave too few results because the second filter ran on the already-filtered list. Calling setRestaurants(resList) first didn't help: inside this click handler restaurants is a snapshot from the current render. The setter queues a change for the next render; it never mutates the variable you're holding.
Fix in your notes: say “state is a snapshot and updates are batched” rather than “useState is asynchronous”. Also, the warning “changing an uncontrolled input to be controlled” comes from value={undefined} on first render. Initial "" fixes it. And useState(default) only uses the default on the first render.
Predict the output
Reveal

Logs 0. Count becomes 1, not 3, with one re-render. All three calls read the same snapshot (count = 0) and React batches them.

To get 3, use the updater form: setCount(c => c + 1) three times. Each updater receives the latest queued value.

SDE-2 upgrade
Don't store what you can compute. Keep allRestaurants and searchText in state, and derive the filtered list during render: const visible = all.filter(...). Fewer states, no sync bugs. Wrap in useMemo only if the list is large.

★Interview cards

Episode-06

Exploring the World

In one breath: Render something immediately, then fetch data in useEffect, show a shimmer while waiting, and re-render when the data arrives.

★Two ways to load a page

Fetch → render
Call API (300ms), then render (200ms). User stares at a blank screen for 500ms.
Render → fetch → re-render ✓
Render skeleton (100ms), fetch (300ms), re-render (200ms). 600ms total, but the user sees UI instantly. Better perceived performance.

The lecture also covers architecture: a monolith ships UI, API, auth, DB access as one deployable; microservices split them into independently deployed services (UI service, API, notifications…) talking over the network. Separation of concerns and single responsibility at system level.

★useEffect timeline

render #1data = []→ Shimmer paintuser seesskeleton effect runsfetchData() network ~300ms setList(json)schedulesre-render render #2cards painteffect skipped(deps [] ) “Initial render” logs before “useEffect called” even though useEffect is written first.
Dependency arrayEffect runs…
omitted useEffect(fn)after every render
[]once, after the first render (mount)
[searchText]after mount, then whenever searchText changes (compared with Object.is)
return () => {...}cleanup: before the next run and on unmount
Shimmer UI

A skeleton that looks like the final layout. Better perceived speed than a spinner or blank screen, and no layout shift when data arrives.

CORS

A browser rule: a page can only read cross-origin responses if the server allows it via Access-Control-Allow-Origin. The extension in class is a dev hack; real fixes are server headers or a proxy (your own backend / dev-server proxy).

Conditional rendering

Ternary a ? <X/> : <Y/>, logical cond && <X/>, or an early return. Early returns must come after all hooks.

Gotcha: && with numbers
{list.length && <List/>} renders a literal 0 when the list is empty. Use list.length > 0 && ... or a ternary.
Fix in your notes: the effect isn't “called every time useState is called”. Without a dependency array it runs after every render, whatever caused it (state, props, or parent re-render). Also: in development with <StrictMode>, React 18+ mounts, unmounts and re-mounts once, so a [] effect runs twice. That's intentional, to surface missing cleanups. Production runs it once.
Predict the output
Reveal

render → effect "" → (type “a”) → render → cleanup "" → effect "a".

Cleanup sees the old value: each effect closes over its own render's snapshot. Rendering always happens before effects.

JSX takes expressions only. {cond ? a : b} works; {if (cond) ...} doesn't. Statement test: type it in the console; if it produces a value, it's an expression.

Re-render scope: when Body's state changes, Body and its children re-run. The parent AppLayout does not.

★Interview cards

Episode-07

Finding the Path

In one breath: react-router-dom maps URLs to components. Nested routes render into an Outlet, dynamic segments are read with useParams, and Link navigates without reloading.

★Rules of hooks (and why)

Never
  • call hooks inside if, loops, or nested functions
  • call hooks outside a component / custom hook
  • define a component inside another component
Why

React stores hook state as an ordered list on the fiber and matches them by call order each render. Skip one conditionally and every later hook gets the wrong state.

A component defined inside another is a new function each render, so React sees a different type, unmounts it and loses its state.

Images: import local files from src/assets (import logo from "../assets/logo.png"), but production apps like Swiggy serve images from a CDN (Cloudinary): cached at the edge, optimized per device, high uptime.

★The route tree

path: "/" element: <AppLayout/> <Header /> (always visible) <Outlet /> matched child renders here errorElement: <Error/> <Footer /> "/" → <Body /> "/about" → <About /> "profile" (relative!) → <Profile/> "/contact" → <Contact /> "/restaurants/:resId" → <RestaurantMenu/>
Nested children render inside their parent's Outlet. “profile” under “/about” resolves to /about/profile; “/profile” would be absolute.
Server-side routing
Every URL change asks the server for a new HTML document. Full reload, state lost.
Client-side routing (SPA)
All components already shipped; the router updates the URL with the History API and swaps components. No document request.

Link vs <a>: <Link> renders an <a> in the DOM but intercepts the click and calls history.pushState, so the page doesn't reload. A raw <a href> reloads everything.

Shimmer keys
For a fixed list of skeleton cards, key={index} is fine: the list never reorders or changes identity.
Fix in your notes: the line says “If we load a path that has been defined…” → should be “not defined” for the 404 error page. Also React Router v7 merged packages: new code can import everything from "react-router"; react-router-dom still works as a re-export. Use <Route index> / { index: true, element: <Body/> } for the default child.

★Interview cards

Episode-08

Let's get Classy

In one breath: Class components are the older way. Know their lifecycle (render phase vs commit phase), how setState works, and why cleanup matters in an SPA.

★Class vs function, side by side

this.setState({ count: 1 })
Shallow-merges into the state object; other keys are kept. Never write this.state.count = 1.
setCount(1)
Replaces the value. For an object state you must spread: setUser(u => ({...u, name})).

★The lifecycle diagram (mounting is the must-know)

Mounting Updating Unmounting Renderpure, canpause/restart Committouches DOM,side effects OK constructor() render() React updates DOM & refs componentDidMount() new props, setState() render() React updates DOM & refs componentDidUpdate() componentWillUnmount()
Source idea: projects.wojtekmaj.pl/react-lifecycle-methods-diagram
Predict the order: parent class with two class children
Reveal
  1. Parent constructor
  2. Parent render
  3. First constructor
  4. First render
  5. Second constructor
  6. Second render
  7. — one batched DOM commit —
  8. First didMount
  9. Second didMount
  10. Parent didMount

React finishes the render phase for the whole subtree first (cheap), then does one commit (expensive DOM work), then runs didMounts children first, because a parent is only “mounted” once its children are. If a child's didMount is async, anything after its await logs after “Parent didMount”.

★Cleanup: the SPA trap

Navigating away in an SPA doesn't reload the page; it just unmounts components. An interval started on mount keeps running. Come back and you have two intervals, then three…

Why not useEffect(async () => …)?
An async function always returns a Promise. React expects the effect to return a cleanup function or nothing. Define an async function inside and call it.
Fix in your notes: componentDidUpdate is not called after the initial render; it only runs after updates. So it's not “like an empty dependency array” — componentDidMount is the closest to [], and componentDidUpdate + prev-value checks is the closest to [deps]. And as the notes say: don't map lifecycles 1:1 to hooks. Effects are about synchronizing with something external, not about moments in time.
Still class-only in 2026

Error boundaries: static getDerivedStateFromError() + componentDidCatch(). No hook equivalent; libraries like react-error-boundary wrap a class for you. They catch errors during rendering and lifecycles, not in event handlers or async code.

★Interview cards

Episode-09

Optimizing our App

In one breath: Pull stateful logic into custom hooks (single responsibility), and split the bundle so users only download code for the page they open.

★Custom hooks

A custom hook is a function whose name starts with use and that calls other hooks. It reuses logic, not state: two components calling useOnlineStatus() each get their own state.

  • Readable, reusable, maintainable, testable.
  • Live in src/utils/ (or hooks/), file named useSomething.js, named export preferred.

The component shrinks to: const resInfo = useRestaurantMenu(resId); if (!resInfo) return <Shimmer/>; Rendering and fetching are now separate concerns.

Fix in your notes: a custom hook isn't a “child component”. Its state lives on the component that calls it, so when the hook's state changes, the calling component re-renders (and its children). Also initialize with navigator.onLine rather than true, so a page that loads offline shows the right status.

★Code splitting with lazy + Suspense

Also called chunking, dynamic bundling, lazy loading, on-demand loading, dynamic import. One giant bundle means users download Instamart's code even if they never open it.

before: one bundle index.js Header BodyAbout MenuInstamart Grocery downloaded on every visit after: chunks index.[hash].js loads at start Instamart.[hash].js loads on navigation Suspense fallback shimmer while promise pending <Instamart /> import() promise resolved user clicks “Instamart” → network request for the chunk
  • import() returns a Promise. Without Suspense, React has nothing to render while it's pending and throws.
  • lazy expects a module with a default export. For a named one: lazy(() => import("./X").then(m => ({ default: m.X }))).
  • Never call lazy() inside a component: a new lazy component each render means remount and state loss.
  • Split by route first (biggest win), then by heavy widgets (charts, editors, maps).

★Interview cards

Episodes 10 to 13 (bonus)

The rest of Season 1, fast

In one breath: Style with Tailwind, share data with Context, manage app-wide state with Redux Toolkit, and prove it works with Jest + React Testing Library. Your notes stop at 9; panels don't.

★Ep 10 — Jo dikhta hai, vo bikta hai (styling)

Options: plain CSS, SCSS, CSS modules, styled-components / CSS-in-JS, component libraries (MUI, Chakra, shadcn), and Tailwind. Tailwind = utility classes (flex p-4 bg-pink-100 rounded-lg) compiled by PostCSS; only classes you use end up in the CSS.

Tailwind pros
Fast to write, no naming, tiny CSS, consistent design tokens.
Tailwind cons
Long class strings, learning curve, markup gets noisy.

★Ep 11 — Data is the new oil

Higher-order component

A function that takes a component and returns an enhanced one. withPromotedLabel(RestaurantCard) adds a “Promoted” badge without touching the card.

Lifting state up

Accordion: each category shouldn't own “am I open?”. The parent holds showIndex and passes isOpen + setShowIndex down. Children become controlled.

Props drilling → Context

Passing user through five layers that don't use it is drilling. createContext + <Ctx.Provider value> + useContext(Ctx) lets any descendant read it. Class components use <Ctx.Consumer>.

Context performance gotcha
Every consumer re-renders when the Provider's value changes identity. Passing a fresh object literal each render re-renders all consumers. Memoize the value or split contexts.

★Ep 12 — Let's build our store (Redux Toolkit)

Component“Add +” clicked dispatch(action)addItem(pizza) reducer fnin cartSlice store (configureStore) cart sliceuser slice useSelectorsubscribe → re-render
Classic question
useSelector(store => store) works but re-renders the component on any store change. Select narrowly. And state = [] inside a reducer does nothing: reassigning the local parameter doesn't mutate the draft. Mutate it or return a new value.

★Ep 13 — Time for the test

TypeTestsTools
UnitOne component/function in isolationJest + React Testing Library
IntegrationSeveral components together (search filters cards)Jest + RTL, mocked fetch
End-to-endReal browser, real user flowPlaywright, Cypress

Setup in the course: jest, babel-jest, @babel/preset-env/react, jest-environment-jsdom, @testing-library/react, @testing-library/jest-dom, plus a .parcelrc so Parcel's own Babel handling doesn't conflict with your babel.config.js. RTL philosophy: test what the user sees, query by role/label/text, not by class names.

★Interview cards

Beyond the course

SDE-2 deep cuts

What changes at SDE-2: they expect why and trade-offs, not definitions. Explain re-render causes, when memoization pays off, how you'd structure state, and how you'd measure performance.

★Why did this re-render?

  1. Its own state changed (via setter, and the new value isn't Object.is-equal).
  2. Its parent re-rendered (props “changing” doesn't matter; parent rendering is enough).
  3. A context it reads changed value.
  4. A store it subscribes to (Redux selector) returned a new value.

★Memoization toolbox

ToolCachesUse when
React.memo(Comp)A component's render, skipped if props are shallow-equalExpensive child re-rendering because of an unrelated parent update
useMemo(fn, deps)A computed valueHeavy computation, or keeping an object/array prop referentially stable for a memo child
useCallback(fn, deps)A function referencePassing callbacks to React.memo children or as effect deps

Measure first with the React DevTools Profiler. Memoizing everything adds comparison cost and memory. The React Compiler now auto-memoizes at build time, which is shifting this advice further toward “write plain code”. Other levers: list virtualization (react-window), debouncing input, moving state down (colocation), splitting a component so the fast-changing part is small.

★State management ladder

useStatelocal, one component lift state upsiblings share Contexttheme, auth, locale Redux / Zustand frequent, app-wide updates server state is different: TanStack Query / RTK Query (cache, refetch)

★React 18 and 19, what to name-drop correctly

React 18
  • createRoot + concurrent rendering
  • Automatic batching everywhere (timeouts, promises too)
  • useTransition / startTransition: mark an update non-urgent so typing stays snappy
  • useDeferredValue: lagging copy of a value for slow children
  • Streaming SSR with Suspense, selective hydration
  • useId, useSyncExternalStore
React 19
  • Actions: async functions in transitions; <form action={fn}>
  • useActionState, useFormStatus, useOptimistic
  • use(promise | context) — can be called conditionally
  • ref as a normal prop (no forwardRef needed)
  • Server Components + Server Functions (via frameworks)
  • <title>/<meta> hoisted from components

★Rendering strategies

HTML builtGood forCost
CSRIn the browser (our Parcel app)Dashboards, logged-in appsBlank first paint, weaker SEO
SSROn server per request, then hydratedPersonalized, SEO pagesServer load, TTFB
SSGAt build timeDocs, blogs, marketingRebuild to update
ISRStatic, revalidated in backgroundCatalogs, listingsBriefly stale data
RSCComponents run on server, ship zero JSData-heavy, mostly static UINew mental model, framework needed

Hydration = React attaching event handlers to server-rendered HTML. If the first client render differs (e.g. Date.now(), window checks), you get a hydration mismatch.

★Hooks you must also know

useRef

A mutable box { current } that survives renders and doesn't trigger re-render. DOM access (inputRef.current.focus()), timer IDs, previous values.

useLayoutEffect

Runs after DOM mutation but before paint, synchronously. For measuring layout (tooltip position) to avoid flicker. Blocks paint, so use sparingly.

useReducer

For state with several related fields and named transitions. dispatch({ type: "added" }). Easier to test; same idea as Redux, locally.

Classic: the stale closure
Reveal

It shows 1 forever. The interval callback was created in the first render, where count is 0, so it keeps setting 0 + 1.

Fix: setCount(c => c + 1). Adding count to deps also works but recreates the interval every second.

★Fetching correctly (race conditions)

★Patterns worth naming

  • Compound components: <Tabs><Tabs.List/><Tabs.Panel/></Tabs> sharing state via context.
  • Controlled vs uncontrolled: parent owns value via props, or the DOM/component owns it (defaultValue, refs).
  • Render props / HOCs: older logic-sharing patterns, mostly replaced by custom hooks.
  • Reset with key: <Profile key={userId} /> remounts and clears state when the user changes.
  • Portals: createPortal(child, document.body) for modals and tooltips that must escape overflow: hidden; events still bubble through the React tree.

★Machine-coding round checklist

usual asks

Debounced autocomplete, infinite scroll (IntersectionObserver), pagination, nested comments, accordion, tabs, star rating, OTP input, image carousel, todo with filters, file explorer tree, progress bar, modal.

what scores points
  1. Clarify requirements and edge cases first (empty, loading, error, very long lists).
  2. Sketch the component tree and where state lives before typing.
  3. Get it working, then clean: custom hook for logic, small presentational components.
  4. Handle loading/error/empty states and stale requests.
  5. Accessibility: real <button>s, labels, keyboard support, aria-expanded.
  6. Talk about what you'd optimize and test with more time.

Web Vitals to mention: LCP (load), INP (responsiveness, replaced FID in 2024), CLS (layout shift). Shimmers help CLS when they match the final layout.

★Interview cards

Beyond the course

Frontend security

In one breath: never trust anything that crosses a boundary. Encrypt the pipe (HTTPS), treat every input as hostile and encode every output for its context (XSS), make sure requests are really intended (CSRF), keep tokens where scripts can't steal them, and tell the browser your rules with headers (CSP, HSTS, frame-ancestors).

★HTTPS: what the padlock really means

TLS gives you three things: encryption (nobody on the Wi-Fi can read it), integrity (nobody can change it in transit) and authentication (the server proved it owns the domain via a certificate). It does not make your app secure; it only secures the pipe.

Browser Server 1. ClientHello TLS versions, cipher suites, key share 2. ServerHello + certificate + key share certificate is signed by a CA the browser trusts 3. Browser checks CA chain, hostname, expiry both sides derive the same symmetric session key (ECDHE) 4. Encrypted HTTP, using fast symmetric crypto
TLS 1.3, simplified. Asymmetric crypto proves identity and agrees on a key; symmetric crypto (AES-GCM) carries the data because it's much faster.
MITM + HSTS

An attacker on the network can downgrade http:// links before the redirect to HTTPS happens. Strict-Transport-Security tells the browser to use HTTPS only for this domain from now on. The very first visit is still exposed, which is why the HSTS preload list exists.

mixed content

An HTTPS page loading HTTP scripts or iframes. Browsers block active mixed content and upgrade or flag images. One HTTP script can rewrite the whole “secure” page.

★Same-origin policy and CORS (deeper than Ep 6)

An origin is protocol + host + port. Scripts can freely send many cross-origin requests, but can only read the response if the server opts in with CORS headers.

Compared with https://app.comSame origin?Why
https://app.com/cartYesPath doesn't matter
http://app.comNoDifferent protocol
https://api.app.comNoDifferent host (subdomains count)
https://app.com:8443NoDifferent port
Simple request (no preflight)

GET, HEAD or POST, only safelisted headers, and Content-Type is form-urlencoded, multipart or text/plain. Sent straight away; the browser just checks the response headers.

Preflighted request

PUT/DELETE/PATCH, custom headers like Authorization, or application/json. The browser first sends OPTIONS; cached with Access-Control-Max-Age.

Access-Control-Allow-Origin: https://app.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Vary: Origin

With credentials the origin must be exact, never *. Vary: Origin stops a cache serving one origin's answer to another.

Trick question alert
“Does CORS protect my API?” No. CORS is enforced by browsers to protect users. curl, Postman and server code ignore it. And simple requests still reach your server and change data even when the response is blocked, so CORS is not CSRF protection either.

★XSS: the most-asked topic

Cross-site scripting means an attacker's JavaScript runs on your origin. From there it can read the DOM and localStorage, call your APIs as the user, and fake login forms.

stored

The payload is saved on the server (a comment, a username) and served to every visitor. The most damaging kind.

reflected

The payload is in the URL (?q=<script>) and the server echoes it into the page. The victim has to click a crafted link.

DOM-based

Never touches the server: client JS reads location.hash or postMessage data and writes it into a sink like innerHTML.

React escapes everything inside {}, so most XSS questions become “where can it still leak?”

Defense in depth: encode output by default (React does), sanitize the rare HTML you must render (DOMPurify), validate URL protocols, add a strict CSP so an injected script still can't run, and keep tokens in HttpOnly cookies so a successful XSS can't steal them.
Spot the hole
Reveal

DOM-based XSS. ?q=<img src=x onerror=alert(document.cookie)> runs code. (A plain <script> tag won't execute via innerHTML, but event-handler attributes do.)

Fix: textContent instead of innerHTML, or render it through JSX.

★Input validation, sanitization, output encoding

StepWhat it doesExample
ValidationRejects input that doesn't match the expected shapeAge must be an integer 0–120; email must match a pattern
SanitizationCleans input by removing dangerous partsDOMPurify strips <script> and onerror from rich-text HTML
Encoding / escapingMakes data safe for the specific place it's outputHTML body: &lt;. URL: encodeURIComponent. JS: JSON.stringify

Client-side validation is for user experience only; anyone can bypass it with DevTools or curl. The server must validate again. Encoding depends on context: what's safe in HTML text is not safe inside an attribute, a URL or a script.

★Security headers and CSP

HeaderWhat it doesTypical value
Content-Security-PolicyAllowlists where scripts, styles, frames, images can come from; blocks inline scriptssee below
Strict-Transport-SecurityHTTPS only, for future visitsmax-age=31536000; includeSubDomains; preload
X-Content-Type-OptionsStops MIME sniffing (a .txt upload run as script)nosniff
X-Frame-OptionsStops your page being framed (clickjacking); CSP frame-ancestors is the modern versionDENY or SAMEORIGIN
Referrer-PolicyLimits how much of the URL leaks to other sitesstrict-origin-when-cross-origin
Permissions-PolicyTurns off browser features you don't usecamera=(), geolocation=()
Cross-Origin-Opener-PolicyIsolates your window from cross-origin popupssame-origin

The nonce must be random and new on every response, otherwise an attacker just copies it. Roll out with Content-Security-Policy-Report-Only first to see what would break. Trusted Types (require-trusted-types-for 'script') goes further and makes DOM sinks like innerHTML refuse plain strings.

Bonus point
X-XSS-Protection is dead. Browsers removed the XSS auditor; saying “use CSP instead” shows you're current.

★Authentication, authorization and tokens

Authentication: who are you?

Login, passwords, OTP, OAuth/SSO. Failure is 401 Unauthorized (the name is misleading: it means “not authenticated”).

Authorization: what may you do?

Roles, permissions, ownership checks. Failure is 403 Forbidden. Must happen on the server for every request.

Session cookie

Server stores the session, browser holds an ID. Easy to revoke (delete the session). Sent automatically, so it needs CSRF protection.

JWT

header.payload.signature, base64url-encoded, not encrypted: anyone can read the payload. Stateless and easy to scale, but hard to revoke before expiry, so keep it short-lived.

Where do tokens live?

StorageJS can read it?Sent automatically?Lasts untilMain risk
localStorageYesNoCleared manuallyAny XSS can steal it
sessionStorageYesNoTab closesSame as localStorage, per tab
Cookie, HttpOnlyNoYes, to its domainExpiryCSRF (fix with SameSite + token)
In-memory variableOnly your running codeNoRefreshLost on reload, so pair with a refresh cookie
Cookie attributeMeaning
HttpOnlyNot visible to document.cookie, so XSS can't read it
SecureOnly sent over HTTPS
SameSite=StrictNever sent on cross-site requests, even when clicking a link from another site
SameSite=LaxSent on top-level GET navigations only. Chrome and Edge use this when SameSite is missing
SameSite=NoneSent everywhere; requires Secure. Needed for third-party embeds
__Host- prefixCookie must be Secure, have Path=/ and no Domain, so subdomains can't overwrite it
SDE-2 nuance: HttpOnly stops XSS from stealing the token, not from using it. Injected script can still call your API from the victim's tab. That's why CSP and output encoding still matter. For OAuth in SPAs, use Authorization Code + PKCE; the old implicit flow put tokens in the URL.

★CSRF: the request you didn't mean to send

Your browser logged in to bank.com cookie: session=abc evil.com hidden auto-submitting form 1. you open the page 2. POST bank.com/transfer browser attaches the bank cookie automatically bank.com valid session, so it obeys 3. money moves attacker never saw the cookie
CSRF abuses automatic cookies. The attacker can trigger the request but can't read the response.
defenses
  1. SameSite cookies (Lax or Strict), set explicitly rather than relying on browser defaults.
  2. CSRF token: a random value the server issues and checks on every state-changing request (synchronizer token, or double-submit cookie).
  3. Check the Origin / Referer header on the server.
  4. Never change state with GET. Require a custom header (like X-Requested-With) or JSON, which forces a preflight that evil.com can't pass.

XSS vs CSRF in one line: XSS runs the attacker's code on your site; CSRF makes the user's browser send a request to your site from somewhere else. If you have XSS, CSRF tokens don't save you, because the script can read the token.

★Iframes: clickjacking and postMessage

your site inside their frame

Clickjacking: the attacker loads your page in an invisible iframe over a “Win a prize” button, so the user really clicks your “Delete account”. Fix with frame-ancestors 'none' (or 'self') in CSP, plus X-Frame-Options for old browsers.

their frame inside your site

Use sandbox to strip powers, then add back only what's needed (allow-scripts, allow-forms). Never combine allow-scripts + allow-same-origin for same-origin content: the frame can remove its own sandbox.

Related: target="_blank" links used to give the new tab window.opener access (reverse tabnabbing). Modern browsers imply rel="noopener" now, but writing it explicitly is still a good answer.

★SRI: trusting a CDN without trusting it

If one byte of the file changes (CDN hacked, file swapped), the browser refuses to run it. Needs an exact pinned version, and crossorigin="anonymous" so the browser can check a cross-origin file. Real example: in 2024 the polyfill.io domain changed owners and started serving malicious code to the sites that loaded it. It generated different code per browser, so it couldn't be pinned with SRI at all: the lesson is to self-host or pin scripts you don't control.

★Server-side ones a frontend dev should know

These show up because frontend engineers now write Node, Next.js API routes and backend-for-frontend layers.

SSRF

Server-Side Request Forgery: your server fetches a URL the user controls, like a link-preview route /api/preview?url=. The attacker passes http://169.254.169.254/ (cloud metadata with credentials) or http://localhost:6379.

Fix: allowlist hosts, resolve DNS and block private IP ranges, don't follow redirects blindly, set timeouts.

SSJI

Server-Side JavaScript Injection: user input executed as code in Node. Sinks: eval, new Function, setTimeout("string"), the vm module (not a security sandbox), Mongo $where.

Fix: never execute input. Use JSON.parse, a safe expression parser, and type-check inputs so {"$gt": ""} can't sneak into a query.

★The “much more” list

  • Secrets in env vars: anything prefixed VITE_, NEXT_PUBLIC_ or REACT_APP_ is baked into the bundle and public. Real secrets stay on a server; the browser calls your backend, which calls the third party.
  • Supply chain: commit the lock file, run npm audit, use Dependabot/Renovate, review new dependencies, prefer npm ci in CI.
  • Open redirect: /login?next=https://evil.com. Allow only relative paths or an allowlist of hosts.
  • Prototype pollution: a naive deep merge of {"__proto__": {"isAdmin": true}} adds isAdmin to every object. Skip __proto__/constructor keys, use Object.create(null) or Map.
  • Sensitive data in the client: don't trust hidden fields, prices or roles sent from the browser; the server recomputes them.
  • Rate limiting and brute force on login and OTP endpoints, with a generic “invalid email or password” message so you don't reveal which accounts exist.

★Scenario round

a typical senior question

“You're building a comment section that supports bold, italics and links. Walk me through every security concern.”

what scores points
  1. Store the raw input; sanitize with an allowlist (DOMPurify: only b, i, a) or, better, store Markdown and render it safely.
  2. Validate link protocols (http/https only), add rel="noopener nofollow ugc".
  3. Strict CSP as a second layer in case sanitization misses something.
  4. Auth on create; authorization on edit/delete (only the owner or a moderator), enforced on the server.
  5. CSRF protection on the POST, rate limiting against spam, length limits.
  6. Tokens in HttpOnly cookies so one missed XSS doesn't leak sessions.

★Interview cards

Write it from scratch

JavaScript polyfills

What they're really testing: do you know the spec well enough to rebuild it? Handle this correctly, cover edge cases (empty arrays, holes, no initial value, errors), keep the original's return value, and narrate as you type. Every snippet here runs as written.
Interview habits
Name it myMap, not map, so you don't overwrite the real one. Write a regular function, never an arrow, when attaching to a prototype, because you need this. Start by stating the signature and edge cases out loud.

★Promise from scratch

The four ideas they want to hear: a promise settles once (pending → fulfilled or rejected), then callbacks are queued until it settles, callbacks always run asynchronously as microtasks, and then returns a new promise resolved with whatever the callback returns (including adopting a returned promise). That last one is what makes chaining work.

If time is short, drop thenable adoption and finally; the state machine, the handler queue, queueMicrotask and returning a new promise from then are the core.

★Promise.all, allSettled, race, any

MethodFulfils whenRejects whenEmpty input
allEvery input fulfils (array, in input order)The first input rejectsFulfils with []
allSettledEvery input settles (array of {status, value | reason})NeverFulfils with []
raceThe first input to settle fulfilsThe first input to settle rejectsStays pending forever
anyThe first input fulfilsEvery input rejects (AggregateError)Rejects with AggregateError
Two bugs interviewers watch for: pushing results in finish order instead of writing results[i], and checking results.length === items.length to detect completion (assigning index 4 first makes length 5 immediately). Use a remaining counter. Wrapping each item in Promise.resolve lets plain values like 3 work too.

★map, filter, reduce, forEach

edge cases to mention

i in this skips holes in sparse arrays ([1, , 3]), matching the real methods. Length is read once at the start. A callback that isn't a function throws a TypeError.

reduce specifically

No initial value: the first element is the accumulator and the loop starts at index 1. Empty array with no initial value throws. Use rest params (...init) so an explicit undefined initial value still counts as provided.

Classic: what does this print?
Reveal

[1, NaN, NaN]. map passes (value, index, array), and parseInt takes (string, radix). So it runs parseInt("1", 0) (radix 0 means default, so 1), parseInt("2", 1) (radix 1 is invalid, NaN) and parseInt("3", 2) (3 isn't a binary digit, NaN).

Fix: .map(Number) or .map((s) => parseInt(s, 10)).

★call, apply, bind

call / apply

Invoke the function right now with a chosen this. call(ctx, a, b) takes arguments one by one; apply(ctx, [a, b]) takes an array.

bind

Doesn't call anything. Returns a new function with this fixed and optionally some arguments preset (partial application). A bound function can't be re-bound.

Arrow functions ignore all three for this; they take this from where they were defined. The new.target branch is the detail that separates a good bind answer from an average one.

★once

★Debounce and throttle

events throttle debounce typing, scrolling, resizing once per 100 ms, the last one with the latest input once, 100 ms after the last event wait
Throttle limits the rate during the burst; debounce waits for the burst to end.
Use debounce for

Search-as-you-type, autosave, validating a field, window resize when you only care about the final size.

Use throttle for

Scroll position, infinite-scroll checks, drag and mousemove, rate-limiting a button. Things that need updates during the activity.

In React, create the debounced function once (useMemo or useRef) and cancel it in effect cleanup. A new debounce on every render means a new timer every render, so it never fires as intended.

★get and set (lodash style)

The __proto__ check is a nice link back to the security page: a naive set is exactly how prototype pollution happens. Optional chaining (a?.b?.[0]?.c ?? "none") replaces get when the path is known at write time.

★memoize

follow-up questions
  • Only for pure functions: same input must always give the same output.
  • Key choice: JSON.stringify fails on functions, cyclic objects and treats different objects with the same contents as equal. Accept a custom resolver, or use a WeakMap keyed by the object for single-object arguments.
  • Memory: the cache grows forever. Mention an LRU limit or TTL.
  • Async functions: cache the promise (so parallel calls share one request) and delete it on rejection so errors aren't cached.

★EventEmitter (pub/sub)

Talking points: on returning an unsubscribe function (like React effect cleanup), copying the array before emitting so once removing itself doesn't skip the next listener, and storing original so off works for once listeners. Forgetting off is a classic memory leak.

★groupBy

★Interview cards

Theory round

Common frontend theory

How to answer theory questions: one-line definition, then why it matters, then a real example from your work, then the trade-off. “Hydration attaches event handlers to server HTML. It matters because… I hit a mismatch when… the fix was…”

★Browser rendering pipeline

HTML CSS DOM CSSOM Render tree Layout Paint Composite visible nodes only size + position pixels per layer GPU joins layers width, top, font size, adding nodes: reflow color, background, box-shadow: repaint transform, opacity: composite only (cheapest)
Each change reruns the pipeline from the stage it affects onward. Animate transform and opacity, not top or width.
  • CSS is render-blocking: the browser won't paint until the CSSOM is ready, because painting unstyled content then restyling is worse.
  • Plain scripts are parser-blocking: the HTML parser stops to download and run them, since a script might call document.write or read styles.
  • display: none elements are in the DOM but not the render tree; visibility: hidden ones are in the render tree and take up space.
Script tagDownloadsRunsOrder kept?
<script>Blocks parsingImmediatelyYes
asyncIn parallelAs soon as it arrives (pauses the parser then)No
deferIn parallelAfter parsing, before DOMContentLoadedYes
type="module"In parallelDeferred by defaultYes

★SSR vs CSR (and friends)

StrategyHTML builtStrengthsCostsFits
CSRIn the browser, from an empty <div id="root">Cheap hosting, app-like navigationBlank page until JS loads, weaker SEO, slower LCPDashboards, apps behind login
SSROn the server, per requestFast first paint, SEO, fresh dataServer cost, TTFB, needs hydrationE-commerce, personalized pages
SSGAt build timeFastest, served from a CDNStale until rebuiltBlogs, docs, marketing
ISRAt build, regenerated in the backgroundStatic speed with periodic freshnessFramework-specific, briefly staleLarge catalogs
Streaming SSR + RSCOn the server, sent in chunksShell paints early, less client JSFramework complexityModern Next.js apps

Trade-off sentence for interviews: SSR improves time to see content, but not necessarily time to use it, because the page isn't interactive until hydration finishes.

★Hydration, and when it fails

Hydration is React taking server-rendered HTML and attaching to it: it renders the same tree in the browser, matches it to the existing DOM nodes instead of recreating them, and wires up event handlers. Done with hydrateRoot. React 18 added selective hydration: with Suspense boundaries, parts hydrate independently and the part the user clicks gets priority.

causes of mismatches
  • Date.now(), new Date(), Math.random() during render
  • Reading window, localStorage, screen size during render
  • Locale or timezone differences between server and browser
  • Invalid HTML nesting (<div> inside <p>), which the browser silently “fixes”
  • Browser extensions injecting markup
fixes
  • Render the client-only value in useEffect after mount (two-pass render)
  • useId for IDs, not counters or random numbers
  • Load client-only components lazily (Next.js: dynamic(..., { ssr: false }))
  • suppressHydrationWarning for one unavoidable text difference, like a timestamp

Why it matters: on a mismatch React throws away the server HTML for that part and re-renders it on the client, losing the SSR performance gain and possibly causing a visible flash.

★The event loop

1 task script, setTimeout, click ALL microtasks promises, await rAF callbacks before the next frame render style, layout, paint if due repeat: pick the next task
JavaScript is single-threaded. The event loop takes one task, empties the whole microtask queue, lets the browser render, and repeats.

Key consequences: a microtask that keeps scheduling microtasks starves rendering (the page freezes), while setTimeout(fn, 0) always waits for the current task and every pending microtask. Web APIs (timers, fetch, DOM events) run outside the JS thread and only queue the callback.

Output order?
Reveal

1, 5, 7, 3, 4, 6, 2. Synchronous code first: 1, then the async function runs synchronously up to its first await (5), then 7. Microtasks in the order they were queued: 3, 4, then the code after await (6). The timer is a new task, so 2 comes last.

★Breaking up long tasks

Any task over 50 ms is a “long task”: clicks and keystrokes wait behind it, which hurts INP. Fixes, from simplest:

  • Yield to the main thread regularly so input and rendering can run in between (below).
  • Web Workers for pure computation (parsing, image processing, search indexes). No DOM access; talk via postMessage.
  • React: useTransition / useDeferredValue so heavy re-renders become interruptible; list virtualization so you render 20 rows, not 10,000.
  • requestIdleCallback for non-urgent work like analytics.

★Event delegation

Events go through three phases: capture (window down to the target), target, then bubble (back up). Delegation uses bubbling: put one listener on a parent instead of one per child. Fewer listeners, less memory, and it works for children added later.

  • e.target is what was actually clicked; e.currentTarget is the element the listener is on.
  • stopPropagation() stops bubbling; preventDefault() stops the browser's default action (link navigation, form submit). They're independent.
  • focus/blur and mouseenter/mouseleave don't bubble; use focusin/focusout and mouseover/mouseout for delegation.
  • React itself delegates: since React 17 it attaches one listener per event type to the root container.

★Garbage collection, memory leaks, WeakMap

JavaScript uses mark-and-sweep: starting from roots (globals, the current call stack), mark everything reachable; whatever isn't marked is freed. Cycles are fine as long as nothing reachable points into them. V8 is generational: most objects die young, so new objects are collected often and cheaply, survivors move to an old space collected less often.

A memory leak in JS is memory that's still reachable but no longer needed.

usual suspects
  • setInterval and listeners never cleared
  • Subscriptions (sockets, stores, emitters) without unsubscribe
  • Detached DOM nodes removed from the page but still referenced in a JS variable
  • Closures holding large objects longer than needed
  • Caches and arrays that only grow
  • Accidental globals (assigning to an undeclared variable)
  • React: effects without cleanup, setState on unmounted components after slow fetches
how to find them
  1. DevTools Memory tab: take a heap snapshot, do the action several times, take another, compare.
  2. Filter the snapshot by “Detached” to find removed DOM nodes still held in memory.
  3. Performance monitor: JS heap size and DOM node count should come back down, not climb steadily.
  4. Read the retainers path to see which reference keeps the object alive.
MapWeakMap
KeysAnythingObjects only (and non-registered symbols)
Holds keysStrongly: keeps them aliveWeakly: if nothing else references the key, the entry disappears
Iterable, sizeYesNo (contents depend on when GC runs)
Use forGeneral key-value dataExtra data attached to objects you don't own: metadata per DOM node, per-object caches, private data

Related: WeakSet (mark objects as seen), WeakRef and FinalizationRegistry (rarely needed, behavior depends on GC timing).

★Core Web Vitals

MetricMeasuresGoodPoorMain fixes
LCP Largest Contentful PaintWhen the main content (hero image, headline) appears≤ 2.5 s> 4 sFaster server/CDN, preload the hero image, avoid render-blocking resources, SSR
INP Interaction to Next PaintDelay from a click/tap/key to the next frame, across the whole visit≤ 200 ms> 500 msBreak long tasks, less JS, cheaper re-renders, debounce
CLS Cumulative Layout ShiftHow much visible content jumps around≤ 0.1> 0.25Width/height or aspect-ratio on media, reserve space for ads and banners, font-display

Judged at the 75th percentile of real visits. Lab tools (Lighthouse) can't measure INP without real users, so they show Total Blocking Time as a proxy; field data comes from real users (CrUX, the web-vitals library). Supporting metrics: TTFB and FCP. INP replaced FID in March 2024.

★Babel and tree shaking

Babel works in three steps: parse code into an AST, transform the AST with plugins (presets are bundles of plugins: preset-env, preset-react, preset-typescript), and generate code plus source maps. preset-env reads browserslist to decide what to transpile; with core-js and useBuiltIns: "usage" it adds only the polyfills your code uses. SWC and esbuild do the same job much faster and are now common defaults.

Tree shaking drops unused exports. It needs ES modules (static import/export), works best with "sideEffects": false in package.json (so the bundler can drop whole unused files), and the minifier removes the dead code at the end. Things that defeat it: CommonJS require, modules with side effects on import, and importing a whole library (import _ from "lodash" instead of import debounce from "lodash/debounce").

★Bundle optimization

ship less
  • Route- and component-level code splitting with lazy() and dynamic import()
  • Analyze first: source-map-explorer, webpack-bundle-analyzer, rollup-plugin-visualizer
  • Replace heavy dependencies (moment → date-fns or native Intl)
  • Target modern browsers so fewer polyfills and less transpiled code ship
ship it faster
  • Brotli/gzip compression, HTTP/2 or 3, a CDN
  • Content-hashed filenames + long Cache-Control so unchanged chunks stay cached
  • Split vendor code that changes rarely from app code that changes often
  • preload what this page needs now, prefetch what the next page will need
  • Images: AVIF/WebP, srcset, loading="lazy" below the fold

★Browser compatibility

  • Decide targets with browserslist (from analytics), check features on caniuse.com or MDN's Baseline status.
  • Syntax is transpiled (Babel/SWC); missing APIs are polyfilled (core-js). Transpiling can't add fetch; polyfilling can't add ?..
  • Feature detection, not browser sniffing: if ("IntersectionObserver" in window) in JS, @supports (display: grid) in CSS.
  • CSS: Autoprefixer (PostCSS) adds vendor prefixes based on the same browserslist.
  • Progressive enhancement: the basic experience works everywhere, extras turn on where supported.
  • Test on real devices or services like BrowserStack, especially Safari on iOS.

★React Fiber, deeper

what a fiber is

A JS object per component instance or element: its type, props, state, effects, and pointers to child, sibling and return (parent). That linked structure lets React walk the tree in a loop and pause between units of work, which a recursive call stack couldn't.

double buffering

React keeps the current tree (on screen) and builds a work-in-progress tree. When the work-in-progress tree is complete, commit swaps them. An interrupted render just throws the unfinished tree away.

priorities (lanes)

Updates get a priority: typing and clicks are urgent, transitions and data loading aren't. React can pause a low-priority render to handle an urgent one, then resume or restart it. That's what powers useTransition and Suspense.

Render phase: interruptible, must be pure (it may run more than once). Commit phase: synchronous, applies DOM changes, then runs layout effects and schedules effects.

★Context API

  • Every consumer re-renders when the value changes by Object.is. Passing {{ theme, setTheme }} inline creates a new object every render, so all consumers re-render every time App does. Memoize it.
  • Split contexts by how often they change (theme vs current user vs cart), or put state and setters in separate contexts.
  • Context isn't a state manager; it's a way to pass a value down. For frequently changing shared state, a store with selectors (Redux, Zustand) avoids re-rendering everyone.
  • React 19: <ThemeContext value={...}> works as the provider directly, and use(ThemeContext) can be called conditionally.

★useEffect vs useLayoutEffect

useEffectuseLayoutEffect
RunsAfter the browser paints (usually)After DOM changes, before paint, synchronously
Blocks painting?NoYes
Use forData fetching, subscriptions, logging, most side effectsMeasuring the DOM and adjusting before the user sees it: tooltip position, scroll restore, avoiding a flicker
On the serverDoesn't runDoesn't run either; can't measure anything there

Default to useEffect; switch only when you see a flicker. Also exists: useInsertionEffect, which runs before layout effects and is meant for CSS-in-JS libraries injecting styles.

★Interview cards

Quick brush-up

HTML & CSS brush-up

The short version: use the element that means what you mean (it gives you accessibility for free), know how a box's size is calculated, know what each position is positioned relative to, and know how the browser picks a winner when rules conflict.

★Semantic HTML

div soup
semantic

Why it matters: screen readers announce landmarks and headings and let users jump between them; search engines understand the structure; and native elements come with behavior built in. A <button> is focusable, works with Enter and Space and is announced as a button. A clickable <div> does none of that.

ElementMeaning
header / footerIntro or closing content for the page or a section
navA major block of navigation links
mainThe page's primary content; one visible per page
articleSelf-contained, could stand alone (post, product card, comment)
sectionA thematic group, normally with its own heading
asideRelated but secondary (sidebar, callout)
figure + figcaption, time, addressCaptioned media, machine-readable dates, contact info
button vs aButton does an action; link goes somewhere (has an href)

Headings form an outline: one h1, then don't skip levels for styling (no h2 → h4). Use real lists, <table> for tabular data, and <label for> for every input.

★Accessibility (a11y)

the essentials
  • Semantic HTML first; it solves most problems
  • Every input has a visible <label>
  • alt text on meaningful images; alt="" on decorative ones
  • Everything works with the keyboard alone: Tab, Shift+Tab, Enter, Space, Esc, arrows
  • A visible focus style; never outline: none without a replacement
  • Text contrast at least 4.5:1 (3:1 for large text)
  • Don't rely on color alone (error = red text and an icon or message)
  • Respect prefers-reduced-motion
ARIA, used carefully
  • First rule of ARIA: don't use it if a native element does the job
  • aria-label / aria-labelledby: name for icon-only buttons
  • aria-describedby: link an input to its error or hint text
  • aria-expanded, aria-controls: accordions, menus
  • aria-live="polite": announce toasts and search result counts
  • aria-hidden="true": hide decorative icons from screen readers
  • tabindex: 0 adds an element to the tab order, -1 makes it focusable only by script (for moving focus to a modal or heading). Never use positive values; they break the natural order.
  • Modals: move focus inside on open, trap Tab within it, close on Esc, return focus to the trigger on close. The native <dialog> with showModal() handles much of this.
  • Testing: axe DevTools or Lighthouse for automated checks (they catch roughly a third of issues), then a keyboard-only pass and a screen reader (VoiceOver on Mac, NVDA on Windows).

★Box model, content-box vs border-box

margin (transparent, outside) border padding (shows background) content content-box (default) width = content only 200 + 2×20 padding + 2×5 border = 250px border-box width = content + padding + border stays 200px; content shrinks to 150px
Example: width: 200px; padding: 20px; border: 5px solid. Margin is never part of the width.

Margin collapse: vertical margins between block siblings (and between a parent and its first or last child, when nothing separates them) merge into the larger one: 20px + 30px gives 30px, not 50px. It doesn't happen in flex or grid containers, or with horizontal margins.

★CSS position

ValueIn normal flow?Offsets (top, left…) are relative toRemember
staticYesIgnoredThe default
relativeYes, original space keptIts own normal positionOften used just to anchor absolute children
absoluteNoNearest ancestor with a non-static position, else the initial containing blockTooltips, badges, overlays
fixedNoThe viewportBreaks if an ancestor has transform, filter or perspective: that ancestor becomes the reference
stickyYesActs relative until it hits the threshold (top: 0) inside its scroll container, then sticksFails with no threshold, or when an ancestor's overflow creates a different scroll container

z-index only compares elements within the same stacking context. New contexts are created by positioned elements with a z-index, opacity below 1, transform, filter, and more. That's why z-index: 9999 sometimes “doesn't work”: its parent's context is underneath.

★CSS units

UnitRelative toGood for
pxFixed (a CSS pixel)Borders, shadows, small details
emFor font-size: the parent's font size. For other properties: the element's own font sizePadding that scales with a component's text. Compounds when nested
remThe root (html) font sizeFont sizes and spacing; respects the user's browser font setting
%Usually the parent. Padding and margin percentages use the parent's width, even top and bottomFluid widths
vw / vh1% of the viewport width / heightFull-screen sections
dvh / svh / lvhDynamic / smallest / largest viewport heightMobile, where 100vh hides behind the browser toolbar
chWidth of the “0” characterReadable line length: max-width: 65ch
frA share of free space in a gridgrid-template-columns: 1fr 2fr

clamp(min, preferred, max) gives fluid sizes with limits: font-size: clamp(1rem, 2.5vw, 2rem). Interview answer for px vs rem: rem text scales when a user raises their default font size; px text doesn't, which is an accessibility problem.

★Cascade, specificity, inheritance

When several rules set the same property on an element, the cascade picks the winner by checking these in order and stopping at the first difference:

  1. Origin and importance: browser defaults < your styles; !important flips the order so important declarations win.
  2. Cascade layers (@layer): later layers beat earlier ones; styles not in any layer beat all layers.
  3. Specificity of the selector.
  4. Order of appearance: the later rule wins.
SelectorSpecificity (IDs, classes, elements)
p0, 0, 1
.card p0, 1, 1
ul li::before0, 0, 3 (pseudo-elements count as elements)
#nav .link:hover1, 2, 0 (pseudo-classes and attributes count as classes)
:where(#nav) p0, 0, 1 (:where() always adds zero)
:is(#nav, .menu) p1, 0, 1 (:is() and :not() take their most specific argument)
style="..."Beats any selector; only !important beats it

Compare left to right like version numbers: one ID beats any number of classes. * and combinators (>, +, ~) add nothing.

Inherited by default

Mostly text-related: color, font-*, line-height, text-align, visibility, cursor, list-style.

Not inherited

Mostly box-related: margin, padding, border, background, width, height, display, position.

Control it with inherit (take the parent's value), initial (the CSS spec default), unset (inherit if the property normally inherits, else initial) and revert (back to the browser's default style). An inherited value always loses to any rule that targets the element directly, however weak its selector.

★Interview cards

Rapid-fire

Rapid-fire drill

Read the question, answer out loud in under 30 seconds, then reveal. Arrow keys work too: → next, ← previous, space to reveal.