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
- JSX → Babel →
React.createElement/jsx()→ plain object → ReactDOM commits to the real DOM. - State change → component function re-runs → new virtual tree → reconciliation (diff) → minimal DOM commit.
- Keys tell the diff which list item is which. Stable IDs, never
Math.random()during render, index only for static lists. - Render phase is pure and can be paused (Fiber). Commit phase touches the DOM and runs effects/lifecycles.
useEffectruns after paint.[]= after mount,[x]= when x changes, none = after every render. Return a cleanup.- State is a snapshot per render; updates are batched. Use
setX(prev => ...)when the next value depends on the old one. - Rules of hooks: top level only, only in components or custom hooks, because React matches hooks by call order.
- Client-side routing swaps components without a document request;
Linknot<a>;Outletrenders child routes. - Class lifecycle: constructor → render → commit → componentDidMount; update → render → componentDidUpdate; componentWillUnmount for cleanup.
- Optimize: custom hooks for logic reuse,
lazy()+Suspensefor 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.
Inception
React.createElement makes a plain object describing UI, and ReactDOM turns that object into real DOM inside one root node.★The three APIs
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.
Tells React “you own everything inside this node”. Returns a root with two methods: render and unmount.
Converts the element tree into DOM and puts it in the root. Existing children of #root get replaced. Returns undefined.
★Things the notes taught
- React is an island. Divs above and below
#rootstay 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(notclass),styleas an object. Unknown lowercase props likehello: "world"also land as attributes. - Multiple children go in an array, and arrays need
keyon each child.
createElement should be camelCase: backgroundColor. The notes wrote "background-color"; React warns about hyphenated style keys (CSS custom properties like --x are the exception).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
Igniting our App
★npm and the files it creates
| File / folder | What it is | Commit to git? |
|---|---|---|
package.json | Project config + dependency ranges (^2.8.2) | Yes |
package-lock.json | Exact installed versions + integrity hash of every package (incl. transitive) | Yes, always |
node_modules/ | The actual code. Heaviest folder, regenerated with npm install | No |
dist/ | Parcel's build output (dev or production) | No |
.parcel-cache/ | Parcel's cache so rebuilds are fast | No |
Rule of thumb: anything that can be regenerated goes in .gitignore.
dependencies
Needed when the app runs:react, react-dom, react-router-dom. npm i reactdevDependencies
Needed only to build/test:parcel, jest, babel plugins. npm i -D parcelnpm vs npx: npm installs and runs scripts; npx parcel index.html executes a package binary without a global install.
★What Parcel does for us
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.
Removes exports you never import. Works because ES module import/export are static and analyzable at build time (CommonJS require is not).
"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→ addtype="module"to the script tag loadingApp.js.You are importing createRoot from "react-dom"→ import from"react-dom/client".- Build fails because
"main": "App.js"conflicts with an HTML entry → deletemainfrom package.json.
Transitive dependencies: your packages depend on other packages, forming a dependency tree. The lock file pins all of them.
"^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.★Interview cards
Laying the Foundation
createElement calls. A functional component is just a function that returns JSX.★npm scripts
★The JSX journey
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
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.
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.
<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.<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.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
Talk is Cheap, Show me the Code
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
★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
- 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).
- ✓ Stable unique ID from data (
res.info.id) - ~ Index: only for static lists that never reorder/filter
- ✗
Math.random()/shortid.generate()inside render
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.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
Let's get Hooked!
useState so React knows when data changed and re-renders the UI.★Folder structure
★Default vs named exports
| Default | Named | |
|---|---|---|
| Export | export default Header; | export const LOGO_URL = "..."; |
| Import | import Header from "./Header"; | import { LOGO_URL } from "./constants"; |
| Per file | Only one | Many |
| Rename on import | Any name works | { LOGO_URL as logo } |
| Both together | import 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.
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.value={undefined} on first render. Initial "" fixes it. And useState(default) only uses the default on the first render.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.
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
Exploring the World
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
| Dependency array | Effect 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 |
A skeleton that looks like the final layout. Better perceived speed than a spinner or blank screen, and no layout shift when data arrives.
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).
Ternary a ? <X/> : <Y/>, logical cond && <X/>, or an early return. Early returns must come after all hooks.
{list.length && <List/>} renders a literal 0 when the list is empty. Use list.length > 0 && ... or a ternary.<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.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
Finding the Path
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)
- call hooks inside
if, loops, or nested functions - call hooks outside a component / custom hook
- define a component inside another component
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
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.
key={index} is fine: the list never reorders or changes identity."react-router"; react-router-dom still works as a re-export. Use <Route index> / { index: true, element: <Body/> } for the default child.★Interview cards
Let's get Classy
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 writethis.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)
Reveal
- Parent constructor
- Parent render
- First constructor
- First render
- Second constructor
- Second render
- — one batched DOM commit —
- First didMount
- Second didMount
- 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…
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.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
Optimizing our App
★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/(orhooks/), file nameduseSomething.js, named export preferred.
The component shrinks to: const resInfo = useRestaurantMenu(resId); if (!resInfo) return <Shimmer/>; Rendering and fetching are now separate concerns.
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.
import()returns a Promise. WithoutSuspense, React has nothing to render while it's pending and throws.lazyexpects 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
The rest of Season 1, fast
★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
A function that takes a component and returns an enhanced one. withPromotedLabel(RestaurantCard) adds a “Promoted” badge without touching the card.
Accordion: each category shouldn't own “am I open?”. The parent holds showIndex and passes isOpen + setShowIndex down. Children become controlled.
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>.
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)
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
| Type | Tests | Tools |
|---|---|---|
| Unit | One component/function in isolation | Jest + React Testing Library |
| Integration | Several components together (search filters cards) | Jest + RTL, mocked fetch |
| End-to-end | Real browser, real user flow | Playwright, 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
SDE-2 deep cuts
★Why did this re-render?
- Its own state changed (via setter, and the new value isn't
Object.is-equal). - Its parent re-rendered (props “changing” doesn't matter; parent rendering is enough).
- A context it reads changed value.
- A store it subscribes to (Redux selector) returned a new value.
★Memoization toolbox
| Tool | Caches | Use when |
|---|---|---|
React.memo(Comp) | A component's render, skipped if props are shallow-equal | Expensive child re-rendering because of an unrelated parent update |
useMemo(fn, deps) | A computed value | Heavy computation, or keeping an object/array prop referentially stable for a memo child |
useCallback(fn, deps) | A function reference | Passing 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
★React 18 and 19, what to name-drop correctly
createRoot+ concurrent rendering- Automatic batching everywhere (timeouts, promises too)
useTransition/startTransition: mark an update non-urgent so typing stays snappyuseDeferredValue: lagging copy of a value for slow children- Streaming SSR with Suspense, selective hydration
useId,useSyncExternalStore
- Actions: async functions in transitions;
<form action={fn}> useActionState,useFormStatus,useOptimisticuse(promise | context)— can be called conditionallyrefas a normal prop (noforwardRefneeded)- Server Components + Server Functions (via frameworks)
<title>/<meta>hoisted from components
★Rendering strategies
| HTML built | Good for | Cost | |
|---|---|---|---|
| CSR | In the browser (our Parcel app) | Dashboards, logged-in apps | Blank first paint, weaker SEO |
| SSR | On server per request, then hydrated | Personalized, SEO pages | Server load, TTFB |
| SSG | At build time | Docs, blogs, marketing | Rebuild to update |
| ISR | Static, revalidated in background | Catalogs, listings | Briefly stale data |
| RSC | Components run on server, ship zero JS | Data-heavy, mostly static UI | New 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
A mutable box { current } that survives renders and doesn't trigger re-render. DOM access (inputRef.current.focus()), timer IDs, previous values.
Runs after DOM mutation but before paint, synchronously. For measuring layout (tooltip position) to avoid flicker. Blocks paint, so use sparingly.
For state with several related fields and named transitions. dispatch({ type: "added" }). Easier to test; same idea as Redux, locally.
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 escapeoverflow: hidden; events still bubble through the React tree.
★Machine-coding round checklist
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.
- Clarify requirements and edge cases first (empty, loading, error, very long lists).
- Sketch the component tree and where state lives before typing.
- Get it working, then clean: custom hook for logic, small presentational components.
- Handle loading/error/empty states and stale requests.
- Accessibility: real
<button>s, labels, keyboard support,aria-expanded. - 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
Frontend security
★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.
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.
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.com | Same origin? | Why |
|---|---|---|
https://app.com/cart | Yes | Path doesn't matter |
http://app.com | No | Different protocol |
https://api.app.com | No | Different host (subdomains count) |
https://app.com:8443 | No | Different 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.
★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.
The payload is saved on the server (a comment, a username) and served to every visitor. The most damaging kind.
The payload is in the URL (?q=<script>) and the server echoes it into the page. The victim has to click a crafted link.
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?”
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
| Step | What it does | Example |
|---|---|---|
| Validation | Rejects input that doesn't match the expected shape | Age must be an integer 0–120; email must match a pattern |
| Sanitization | Cleans input by removing dangerous parts | DOMPurify strips <script> and onerror from rich-text HTML |
| Encoding / escaping | Makes data safe for the specific place it's output | HTML body: <. 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
| Header | What it does | Typical value |
|---|---|---|
Content-Security-Policy | Allowlists where scripts, styles, frames, images can come from; blocks inline scripts | see below |
Strict-Transport-Security | HTTPS only, for future visits | max-age=31536000; includeSubDomains; preload |
X-Content-Type-Options | Stops MIME sniffing (a .txt upload run as script) | nosniff |
X-Frame-Options | Stops your page being framed (clickjacking); CSP frame-ancestors is the modern version | DENY or SAMEORIGIN |
Referrer-Policy | Limits how much of the URL leaks to other sites | strict-origin-when-cross-origin |
Permissions-Policy | Turns off browser features you don't use | camera=(), geolocation=() |
Cross-Origin-Opener-Policy | Isolates your window from cross-origin popups | same-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.
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?
| Storage | JS can read it? | Sent automatically? | Lasts until | Main risk |
|---|---|---|---|---|
| localStorage | Yes | No | Cleared manually | Any XSS can steal it |
| sessionStorage | Yes | No | Tab closes | Same as localStorage, per tab |
Cookie, HttpOnly | No | Yes, to its domain | Expiry | CSRF (fix with SameSite + token) |
| In-memory variable | Only your running code | No | Refresh | Lost on reload, so pair with a refresh cookie |
| Cookie attribute | Meaning |
|---|---|
HttpOnly | Not visible to document.cookie, so XSS can't read it |
Secure | Only sent over HTTPS |
SameSite=Strict | Never sent on cross-site requests, even when clicking a link from another site |
SameSite=Lax | Sent on top-level GET navigations only. Chrome and Edge use this when SameSite is missing |
SameSite=None | Sent everywhere; requires Secure. Needed for third-party embeds |
__Host- prefix | Cookie must be Secure, have Path=/ and no Domain, so subdomains can't overwrite it |
★CSRF: the request you didn't mean to send
- SameSite cookies (
LaxorStrict), set explicitly rather than relying on browser defaults. - CSRF token: a random value the server issues and checks on every state-changing request (synchronizer token, or double-submit cookie).
- Check the
Origin/Refererheader on the server. - 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
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.
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.
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.
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_orREACT_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, prefernpm ciin 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}}addsisAdminto every object. Skip__proto__/constructorkeys, useObject.create(null)orMap. - 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
“You're building a comment section that supports bold, italics and links. Walk me through every security concern.”
- Store the raw input; sanitize with an allowlist (DOMPurify: only
b,i,a) or, better, store Markdown and render it safely. - Validate link protocols (
http/httpsonly), addrel="noopener nofollow ugc". - Strict CSP as a second layer in case sanitization misses something.
- Auth on create; authorization on edit/delete (only the owner or a moderator), enforced on the server.
- CSRF protection on the POST, rate limiting against spam, length limits.
- Tokens in HttpOnly cookies so one missed XSS doesn't leak sessions.
★Interview cards
JavaScript polyfills
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.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
| Method | Fulfils when | Rejects when | Empty input |
|---|---|---|---|
all | Every input fulfils (array, in input order) | The first input rejects | Fulfils with [] |
allSettled | Every input settles (array of {status, value | reason}) | Never | Fulfils with [] |
race | The first input to settle fulfils | The first input to settle rejects | Stays pending forever |
any | The first input fulfils | Every input rejects (AggregateError) | Rejects with AggregateError |
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
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.
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.
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
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
- Only for pure functions: same input must always give the same output.
- Key choice:
JSON.stringifyfails on functions, cyclic objects and treats different objects with the same contents as equal. Accept a custom resolver, or use aWeakMapkeyed 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
Common frontend theory
★Browser rendering pipeline
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.writeor read styles. display: noneelements are in the DOM but not the render tree;visibility: hiddenones are in the render tree and take up space.
| Script tag | Downloads | Runs | Order kept? |
|---|---|---|---|
<script> | Blocks parsing | Immediately | Yes |
async | In parallel | As soon as it arrives (pauses the parser then) | No |
defer | In parallel | After parsing, before DOMContentLoaded | Yes |
type="module" | In parallel | Deferred by default | Yes |
★SSR vs CSR (and friends)
| Strategy | HTML built | Strengths | Costs | Fits |
|---|---|---|---|---|
| CSR | In the browser, from an empty <div id="root"> | Cheap hosting, app-like navigation | Blank page until JS loads, weaker SEO, slower LCP | Dashboards, apps behind login |
| SSR | On the server, per request | Fast first paint, SEO, fresh data | Server cost, TTFB, needs hydration | E-commerce, personalized pages |
| SSG | At build time | Fastest, served from a CDN | Stale until rebuilt | Blogs, docs, marketing |
| ISR | At build, regenerated in the background | Static speed with periodic freshness | Framework-specific, briefly stale | Large catalogs |
| Streaming SSR + RSC | On the server, sent in chunks | Shell paints early, less client JS | Framework complexity | Modern 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.
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
- Render the client-only value in
useEffectafter mount (two-pass render) useIdfor IDs, not counters or random numbers- Load client-only components lazily (Next.js:
dynamic(..., { ssr: false })) suppressHydrationWarningfor 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
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.
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/useDeferredValueso heavy re-renders become interruptible; list virtualization so you render 20 rows, not 10,000. requestIdleCallbackfor 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.targetis what was actually clicked;e.currentTargetis the element the listener is on.stopPropagation()stops bubbling;preventDefault()stops the browser's default action (link navigation, form submit). They're independent.focus/blurandmouseenter/mouseleavedon't bubble; usefocusin/focusoutandmouseover/mouseoutfor 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.
setIntervaland 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
- DevTools Memory tab: take a heap snapshot, do the action several times, take another, compare.
- Filter the snapshot by “Detached” to find removed DOM nodes still held in memory.
- Performance monitor: JS heap size and DOM node count should come back down, not climb steadily.
- Read the retainers path to see which reference keeps the object alive.
| Map | WeakMap | |
|---|---|---|
| Keys | Anything | Objects only (and non-registered symbols) |
| Holds keys | Strongly: keeps them alive | Weakly: if nothing else references the key, the entry disappears |
Iterable, size | Yes | No (contents depend on when GC runs) |
| Use for | General key-value data | Extra 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
| Metric | Measures | Good | Poor | Main fixes |
|---|---|---|---|---|
| LCP Largest Contentful Paint | When the main content (hero image, headline) appears | ≤ 2.5 s | > 4 s | Faster server/CDN, preload the hero image, avoid render-blocking resources, SSR |
| INP Interaction to Next Paint | Delay from a click/tap/key to the next frame, across the whole visit | ≤ 200 ms | > 500 ms | Break long tasks, less JS, cheaper re-renders, debounce |
| CLS Cumulative Layout Shift | How much visible content jumps around | ≤ 0.1 | > 0.25 | Width/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
- Route- and component-level code splitting with
lazy()and dynamicimport() - 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
- Brotli/gzip compression, HTTP/2 or 3, a CDN
- Content-hashed filenames + long
Cache-Controlso unchanged chunks stay cached - Split vendor code that changes rarely from app code that changes often
preloadwhat this page needs now,prefetchwhat 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
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.
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.
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
valuechanges byObject.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, anduse(ThemeContext)can be called conditionally.
★useEffect vs useLayoutEffect
| useEffect | useLayoutEffect | |
|---|---|---|
| Runs | After the browser paints (usually) | After DOM changes, before paint, synchronously |
| Blocks painting? | No | Yes |
| Use for | Data fetching, subscriptions, logging, most side effects | Measuring the DOM and adjusting before the user sees it: tooltip position, scroll restore, avoiding a flicker |
| On the server | Doesn't run | Doesn'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
HTML & CSS brush-up
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.
| Element | Meaning |
|---|---|
header / footer | Intro or closing content for the page or a section |
nav | A major block of navigation links |
main | The page's primary content; one visible per page |
article | Self-contained, could stand alone (post, product card, comment) |
section | A thematic group, normally with its own heading |
aside | Related but secondary (sidebar, callout) |
figure + figcaption, time, address | Captioned media, machine-readable dates, contact info |
button vs a | Button 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)
- Semantic HTML first; it solves most problems
- Every input has a visible
<label> alttext 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: nonewithout 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
- First rule of ARIA: don't use it if a native element does the job
aria-label/aria-labelledby: name for icon-only buttonsaria-describedby: link an input to its error or hint textaria-expanded,aria-controls: accordions, menusaria-live="polite": announce toasts and search result countsaria-hidden="true": hide decorative icons from screen readers
- tabindex:
0adds an element to the tab order,-1makes 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>withshowModal()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
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
| Value | In normal flow? | Offsets (top, left…) are relative to | Remember |
|---|---|---|---|
static | Yes | Ignored | The default |
relative | Yes, original space kept | Its own normal position | Often used just to anchor absolute children |
absolute | No | Nearest ancestor with a non-static position, else the initial containing block | Tooltips, badges, overlays |
fixed | No | The viewport | Breaks if an ancestor has transform, filter or perspective: that ancestor becomes the reference |
sticky | Yes | Acts relative until it hits the threshold (top: 0) inside its scroll container, then sticks | Fails 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
| Unit | Relative to | Good for |
|---|---|---|
px | Fixed (a CSS pixel) | Borders, shadows, small details |
em | For font-size: the parent's font size. For other properties: the element's own font size | Padding that scales with a component's text. Compounds when nested |
rem | The root (html) font size | Font 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 bottom | Fluid widths |
vw / vh | 1% of the viewport width / height | Full-screen sections |
dvh / svh / lvh | Dynamic / smallest / largest viewport height | Mobile, where 100vh hides behind the browser toolbar |
ch | Width of the “0” character | Readable line length: max-width: 65ch |
fr | A share of free space in a grid | grid-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:
- Origin and importance: browser defaults < your styles;
!importantflips the order so important declarations win. - Cascade layers (
@layer): later layers beat earlier ones; styles not in any layer beat all layers. - Specificity of the selector.
- Order of appearance: the later rule wins.
| Selector | Specificity (IDs, classes, elements) |
|---|---|
p | 0, 0, 1 |
.card p | 0, 1, 1 |
ul li::before | 0, 0, 3 (pseudo-elements count as elements) |
#nav .link:hover | 1, 2, 0 (pseudo-classes and attributes count as classes) |
:where(#nav) p | 0, 0, 1 (:where() always adds zero) |
:is(#nav, .menu) p | 1, 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 drill
Read the question, answer out loud in under 30 seconds, then reveal. Arrow keys work too: → next, ← previous, space to reveal.