')}); done(); } });\nconst stream = renderToPipeableStream(app, { onShellReady() { stream.pipe(out); } });\n\nRun in a Playwright v1.48.2 (Node) container with React 18.3.1, it prints:\n\nchunk 1:

Product page

Loading reviews

\nchunk 2: \n\nChunk 1 is the shell with the fallback text in place and an empty template marking where the boundary's content belongs; the browser can paint it immediately. Chunk 2 carries the finished HTML in a hidden div plus a script that swaps it into the template's position, so the slow part never blocked the first paint.\n\nOption 5 made concrete: a list component that stores items and also a total in state keeps two copies that must agree and doubles what is serialised and rebuilt on hydration; computing total from items during render removes the second copy. Memoising a row component (React.memo) means a parent re-render with unchanged props skips those rows.\n\nRecommendation: do option 1 first (cheapest, biggest effect when the state is mostly unused), then option 2 for the two or three heaviest below-the-fold components. Move to option 4 only if the trace shows the page is mostly static after those two steps, because it changes how the team writes components.\n\nThe ordering flips for two cases. If search engines must see the full list in the HTML, keep rendering all of it on the server but hydrate only the first screen (options 2 or 4): HTML is cheap to deliver, hydration is the expensive part. If the slow part is waiting for one slow API rather than hydration, option 3 comes first.\n\nWorked, runnable comparison\n\nThe demo builds two pages and hydrates each in Chromium seven times. The full page has all 3,000 product cards in its server HTML and in its state. The trimmed page is what option 1 produces: both its server HTML and its state hold only the 24 products that fit on the first screen, and the rest would be fetched later. The time is measured from the hydrateRoot call until every card's useEffect has run (effects run after a component has hydrated), so it covers all the work rather than only the first slice. Reading the listings: window.__expected holds how many cards must hydrate and window.__mounted counts the effects that have run; when the counter reaches the expected number, the last card has hydrated and __hydrateMs is the elapsed time since __t0, taken just before hydrateRoot was called. onRecoverableError records any mismatch between server HTML and client render, and the demo fails if one occurs. The state is serialised with < escaped as \\u003c and the first product's text is the string x, which would close the script tag if the escaping were missing.\n\n// app.jsx\nimport React from 'react';\nexport function Card({ p }) {\n const [liked, setLiked] = React.useState(false);\n React.useEffect(() => { // effects run after a component has hydrated\n window.__mounted = (window.__mounted || 0) + 1;\n if (window.__mounted === window.__expected) window.__hydrateMs = performance.now() - window.__t0;\n }, []);\n return (\n
  • \n

    {p.name}

    \n

    {p.blurb}

    \n {p.price.toFixed(2)}\n \n
  • \n );\n}\nexport function App({ products }) {\n return ;\n}\n\n// client.jsx\nimport React from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport { App } from './app.jsx';\nconst state = JSON.parse(document.getElementById('state').textContent);\nwindow.__expected = state.length; window.__t0 = performance.now();\nhydrateRoot(document.getElementById('root'), , {\n onRecoverableError: (e) => { window.__hydrationError = String(e); },\n});\n\n// hydrate-demo.mjs\nimport http from 'node:http';\nimport { build } from 'esbuild';\nimport React from 'react';\nimport { renderToString } from 'react-dom/server';\nimport { chromium } from 'playwright';\n\nconst BREAK = process.env.BREAK || ''; // 'full' sends the whole catalogue in the first load\nconst TOTAL = 3000, ABOVE_FOLD = 24;\nconst products = Array.from({ length: TOTAL }, (_, i) => ({ id: i, name: 'Product ' + i, blurb: i === 0 ? 'x' : 'Description text for product number ' + i + ', repeated detail.', price: 10 + (i % 90) }));\n\nawait build({ entryPoints: ['app.jsx'], bundle: true, platform: 'node', format: 'esm', external: ['react'], outfile: 'dist/server.mjs', logLevel: 'error' });\nconst { App } = await import('./dist/server.mjs');\nawait build({ entryPoints: ['client.jsx'], bundle: true, minify: true, outfile: 'dist/client.js', logLevel: 'error', define: { 'process.env.NODE_ENV': '\"production\"' } });\nconst html = (list) => {\n const state = JSON.stringify(list).replace(/
    ${renderToString(React.createElement(App, { products: list }))}
    };\n};\nconst full = html(products), slim = html(products.slice(0, ABOVE_FOLD));\nconst pages = { '/full': full.page, '/slim': slim.page };\nconst server = http.createServer(async (req, res) => {\n if (req.url === '/client.js') { res.setHeader('content-type', 'text/javascript'); return res.end(await (await import('node:fs/promises')).readFile('dist/client.js')); }\n res.setHeader('content-type', 'text/html'); res.end(pages[req.url] || '');\n}).listen(0);\nconst base = http://localhost:${server.address().port};\n\nconst browser = await chromium.launch();\nasync function hydrateMs(path) {\n const page = await (await browser.newContext()).newPage(); await page.goto(base + path);\n await page.waitForFunction(() => window.__hydrateMs !== undefined);\n const r = await page.evaluate(() => ({ ms: window.__hydrateMs, err: window.__hydrationError })); await page.context().close(); return r;\n}\nconst med = (a) => a.slice().sort((x, y) => x - y)[Math.floor(a.length / 2)];\nconst target = BREAK === 'full' ? '/full' : '/slim';\nconst a = [], b = [];\nfor (let i = 0; i < 7; i++) { const f = await hydrateMs('/full'), s = await hydrateMs(target); a.push(f.ms); b.push(s.ms); if (f.err || s.err) { console.log('hydration error', f.err || s.err); process.exit(1); } }\nconst kb = (s) => (Buffer.byteLength(s) / 1024).toFixed(1);\nconsole.log(state JSON: full ${Buffer.byteLength(full.state)} bytes (${kb(full.state)} KiB), above-the-fold ${Buffer.byteLength(slim.state)} bytes (${kb(slim.state)} KiB));\nconsole.log(hydrate time, median of 7 (ms): full ${med(a).toFixed(0)}, trimmed ${med(b).toFixed(0)});\nconst ok = med(a) > 3 * med(b);\nconsole.log(${ok ? 'PASS' : 'FAIL'}: hydrating ${ABOVE_FOLD} of ${TOTAL} products took ${(med(a) / med(b)).toFixed(1)}x less time);\nawait browser.close(); server.close(); process.exit(ok ? 0 : 1);\n\nOne sample run printed:\n\nstate JSON: full 338639 bytes (330.7 KiB), above-the-fold 2531 bytes (2.5 KiB)\nhydrate time, median of 7 (ms): full 165, trimmed 3\nPASS: hydrating 24 of 3000 products took 50.0x less time\n\nThe byte figures are deterministic and are raw JSON bytes before compression (measure transferred bytes on your own page, as step 1 says, because gzip shrinks repetitive JSON like this): 2,531 / 338,639 = 0.75% of the state remains. The time figures are not: across repeated runs of the same demo the full-state median falls into two clusters, near 30 ms (26 to 31 ms) on some runs and near 170 ms (165 to about 195 ms) on most, while the trimmed median stayed between 3 and 8 ms, giving ratios from 7.1x to 53.7x. The sample run above is one of the slower-cluster runs, so its 50.0x is near the top of that spread and should not be quoted as the result. What holds in every run is the direction and a several-fold gap, which is why the demo asserts only that the ratio is above 3 (and fails if hydration logs a mismatch error). The work itself is deterministic: 3,000 components to hydrate against 24 is 125 times fewer.\n\nThe trade-off made visible: the remaining 2,976 products (3,000 minus 24) now have to come from somewhere, so the client needs a request when the user scrolls, plus a loading state. Complexity moved; it did not vanish.\n\nPitfalls\n\nServer and client state must match at hydration. If the trimmed state renders different markup from the server HTML, React reports a recoverable error and falls back to client rendering, which is slower than before. Running the demo with the full 3,000-card server HTML but the 24-product state does exactly this: onRecoverableError records a hydration error (a minified React error #423 in the production build) and the demo exits 1. So trimming the state is only safe together with trimming the server HTML for the same part of the page, or with a lazy boundary whose fallback matches the server HTML.\nEscape the serialised state. Embedding JSON.stringify output unescaped in a script tag lets a stray in user data end the tag; replacing < with \\u003c is the standard fix and is shown above.\nLazy boundaries need stable placeholders. A fallback with no reserved size shifts the layout when the real component arrives (CLS, Cumulative Layout Shift, the score for unexpected movement).\nDo not hide the cost in effects. Moving work from render into useEffect just delays the same main-thread time to just after hydration.\n\nRunning the code\n\nmkdir demo && cd demo && echo '{\"type\":\"module\"}' > package.json # then save the four listings above here\ndocker run --rm -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c 'npm i --silent react@18.3.1 react-dom@18.3.1 esbuild@0.24.0 playwright@1.48.2 && node hydrate-demo.mjs && node stream-demo.mjs'\nadd -e BREAK=full before the image name to send the full state to both pages: FAIL line, exit code 1\nstream-demo.mjs (in the option 3 section) runs the same way: node stream-demo.mjs\n\nThe printed output comes from the mcr.microsoft.com/playwright:v1.48.2-jammy image (headless Chromium 130.0.6723.31, aarch64 Linux container)."}},{"@type":"Question","name":"Product wants the fastest possible improvement to page load time and gives you four weeks. You're weighing frontend work like lazy-loading and code-splitting against a backend API-aggregation effort. Which would you recommend starting with, and what would change your answer?","acceptedAnswer":{"@type":"Answer","text":"Approach\n\nTrace what actually blocks the page from being usable before picking a side, since page load time is a chain, and lazy-loading (deferring resources until needed) and code-splitting (breaking a large JavaScript bundle into smaller pieces loaded on demand) fix a different part of that chain than API aggregation (combining multiple backend calls into fewer round trips).\n\nWorked estimate (illustrative numbers)\n\nSay a trace shows the page currently loads in 4.5 seconds: about 1.5 seconds comes from a chain of 8 sequential API calls at roughly 180 milliseconds round trip each, about 2 seconds from downloading, parsing, and running a large, unsplit JavaScript bundle, and the remaining second from rendering and images.\n\nAggregating those 8 calls into 2 combined calls could plausibly cut that 1.5 seconds down to 400 to 500 milliseconds, roughly a 1 second win. Code-splitting the bundle so only what is needed for first paint loads up front could plausibly cut the 2 second JavaScript cost by half or more, roughly another 1 to 1.2 second win. In this profile the two options are close in raw impact, so the tie-breaker becomes speed and risk to build in four weeks. API aggregation usually touches fewer moving parts and can ship incrementally, one endpoint at a time, with fast, measurable wins, while a full code-splitting pass across a codebase, deciding what is route-critical versus deferred, tends to take longer to get right.\n\nWhat would change the answer\n\nIf the trace showed one side clearly dominating, say 3 of the 4.5 seconds coming from the sequential API calls, I would start there since it has the higher ceiling. If most users are on a fast connection but a smaller, high-value segment is on mobile or slow networks where the JavaScript payload dominates their experience, that shifts the priority depending on who \"fastest possible\" is really meant to serve. And if the backend calls are shared with other teams' services, aggregating them carries wider blast radius and may take longer to get sign-off on than a frontend-only change, which pushes the four-week bet toward frontend first."}},{"@type":"Question","name":"Explain CSS custom properties (variables): syntax, cascade and inheritance behavior, runtime updates via JavaScript, fallback values, and how they differ from preprocessor variables. Give examples where custom properties simplify theming and reduce duplication.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nA CSS custom property (often called a CSS variable) is a property whose name starts with --, which you declare on any element and read with var(--name). Unlike a preprocessor variable, it lives in the browser: it takes part in the cascade (the rules that decide which declaration wins), it is inherited by descendants, and it can be changed at runtime from CSS or JavaScript, so everything that uses it updates. A Sass or Less variable is substituted when the stylesheet is compiled and is gone by the time the browser sees the CSS.\n\nSyntax, cascade and inheritance\n\nMDN: \"Property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.\" Names are case sensitive: --accent and --Accent are different properties.\n\nCustom properties are \"scoped to the element(s) they are declared on, and participate in the cascade\", and they are inherited. So:\n\nDeclare shared values on :root (the element) and every element sees them.\nRe-declare on a component or attribute selector to change the value for that element and its descendants only; siblings and ancestors are untouched.\n\n:root { --accent: rgb(0, 102, 204); --gap: 8px; }\n[data-theme=\"dark\"] { --accent: rgb(102, 178, 255); }\n.card { color: var(--accent); padding: var(--gap); border: 1px solid var(--accent) }\n.card.warn { --accent: rgb(200, 100, 0); } / this card and its children only /\n\nFallback values and invalid values\n\nvar(--name, fallback) uses the fallback when the property has no usable value, for example when it was never declared. Everything after the first comma is the fallback, so var(--f, Georgia, serif) falls back to Georgia, serif. MDN adds that if a property is registered with @property using a typed syntax and an initial-value, that initial value is used and the fallback is not. Registering means declaring the property's type and default in CSS, for example @property --size { syntax: \"\"; inherits: false; initial-value: 0px; }: the browser then knows --size must be a length and has a default for it, so it is never \"missing\" and the fallback in var(--size, 10px) is never reached. (MDN: syntax and inherits are required, and initial-value is required unless syntax is \"*\".)\n\nIf var() resolves to something invalid for the property it is used in (undefined with no fallback, or a value like 20px for color), the declaration is not dropped at parse time; the browser can only find the problem later, when it computes the value (\"invalid at computed-value time\"). MDN says it is \"treated as if it has value unset\": unset means \"inherit if the property normally inherits, otherwise use the initial value\". The other cascaded values for that property are already discarded, so an inherited property like color inherits from its parent and a non-inherited one resets to its initial value. A literal bad value (color: 20px) is different: it is ignored at parse time, as if the line were not there, and the earlier rule still wins.\n\nA contrast, using rules from the script below. p { color: red; } applies to every paragraph. .literal { color: 20px; } is thrown away while the stylesheet is read, so the paragraph stays red. .bad { --n: 20px; color: var(--n); } parses fine, because the browser cannot know yet that --n is a length, but at computed-value time color: 20px is invalid, the p rule's red is not restored, and the paragraph inherits its parent's colour, which is black here (rgb(0, 0, 0)).\n\nRuntime updates from JavaScript\n\ndocument.documentElement.style.setProperty('--accent', 'tomato'); // every var(--accent) user restyles\ngetComputedStyle(document.documentElement).getPropertyValue('--accent');\ndocument.documentElement.style.removeProperty('--accent'); // back to the stylesheet value\n\nNo elements are re-rendered by your code; the browser recomputes styles. An element that re-declares the property itself (the .warn card above) keeps its own value, because the nearer declaration wins.\n\nCustom properties versus preprocessor variables\n\nCompiling this Sass with Dart Sass 1.77.8:\n\n$accent: #0066cc;\n.card { color: $accent; --accent: #{$accent}; border-color: var(--accent); }\n\ngives\n\n.card {\n color: #0066cc;\n --accent: #0066cc;\n border-color: var(--accent);\n}\n\n$accent has been replaced by its value (compile-time, one value everywhere, no DOM awareness). var(--accent) survives and is resolved in the browser per element. Preprocessors remain useful for things custom properties cannot do: loops, mixins, functions, and computing values at build time. Custom properties cannot be used in property names or selectors, and MDN says var() \"cannot be used in property names, selectors or anything else besides property values.\"\n\nLimitation: not in media query conditions\n\nBecause var() is only valid in property values, @media (min-width: var(--bp)) { ... } never matches. The test below shows it staying unapplied at a 2000px-wide viewport. Keep breakpoints as literals, or use a build step that substitutes them.\n\nTheming and reducing duplication\n\nWithout variables, a dark theme means a second copy of every colour rule. With them, components read semantic names (--surface, --text, --accent), and one block redefines the names:\n\n:root { --surface: #fff; --text: #111; }\n:root[data-theme=\"dark\"] { --surface: #111; --text: #eee; }\n.card, .menu, .modal { background: var(--surface); color: var(--text); }\n\nFlipping data-theme on restyles every component in one step. Component-level knobs work the same way: a .button reads var(--button-bg, var(--accent)), and a page overrides --button-bg on one container. A runtime-switchable colour (a user picking a brand colour) is setProperty('--accent', picked).\n\nVerifying it in three engines\n\nimport { chromium, firefox, webkit } from 'playwright';\nimport assert from 'node:assert/strict';\n\nconst html = `\n\n
    A inner
    \n
    B inner
    \n

    c

    d

    \n

    e

    f

    g

    `;\n\nconst q = (page, sel, prop) => page.evaluate(([s, p]) => getComputedStyle(document.querySelector(s))[p], [sel, prop]);\nconst BLUE = 'rgb(0, 102, 204)', LIGHT = 'rgb(102, 178, 255)', ORANGE = 'rgb(200, 100, 0)';\n\nfor (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {\n const browser = await type.launch();\n const page = await browser.newPage({ viewport: { width: 2000, height: 600 } });\n await page.setContent(html);\n const r = {};\n r.root = await q(page, '#a', 'color');\n r.scoped = [await q(page, '#b', 'color'), await q(page, '#binner', 'color')]; // override inherited by the child\n r.otherCard = await q(page, '#inner', 'color'); // a span in the first card: untouched by the other card's override\n r.fallback = await q(page, '#c', 'color');\n r.multi = await q(page, '#d', 'fontFamily');\n r.bad = await q(page, '#e', 'color'); // unset on an inherited property: inherits from body\n r.literal = await q(page, '#f', 'color'); // the p rule still applies\n r.mq = await q(page, '#g', 'color'); // the media rule never matched, even at 2000px\n r.caseSensitive = await page.evaluate(() => [getComputedStyle(document.documentElement).getPropertyValue('--accent').trim(),\n getComputedStyle(document.documentElement).getPropertyValue('--Accent').trim()]);\n // runtime update from JavaScript: no re-render, the cascade recomputes\n await page.evaluate(() => document.documentElement.style.setProperty('--accent', 'rgb(1, 2, 3)'));\n r.afterJs = [await q(page, '#a', 'color'), await q(page, '#b', 'color')]; // #b keeps its own declaration\n await page.evaluate(() => document.documentElement.style.removeProperty('--accent'));\n // theming: one attribute flip re-points every component\n await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark'));\n r.dark = await q(page, '#a', 'color');\n console.log(name.padEnd(8), JSON.stringify(r));\n assert.equal(r.root, BLUE);\n assert.deepEqual(r.scoped, [ORANGE, ORANGE]);\n assert.equal(r.otherCard, BLUE);\n assert.equal(r.fallback, 'rgb(0, 128, 0)');\n assert.match(r.multi, /^Georgia, serif$/);\n assert.equal(r.bad, await q(page, 'body', 'color'));\n assert.equal(r.literal, 'rgb(255, 0, 0)');\n assert.equal(r.mq, 'rgb(9, 9, 9)');\n assert.deepEqual(r.caseSensitive, [BLUE, 'rgb(204, 0, 0)']);\n assert.deepEqual(r.afterJs, ['rgb(1, 2, 3)', ORANGE]);\n assert.equal(r.dark, LIGHT);\n await browser.close();\n}\nconsole.log('all assertions passed');\n\nRun in the Playwright 1.48.2 image, every engine (Chromium, Firefox, Playwright's WebKit build) printed the same values, shown here for Chromium:\n\nchromium {\"root\":\"rgb(0, 102, 204)\",\"scoped\":[\"rgb(200, 100, 0)\",\"rgb(200, 100, 0)\"],\"otherCard\":\"rgb(0, 102, 204)\",\"fallback\":\"rgb(0, 128, 0)\",\"multi\":\"Georgia, serif\",\"bad\":\"rgb(0, 0, 0)\",\"literal\":\"rgb(255, 0, 0)\",\"mq\":\"rgb(9, 9, 9)\",\"caseSensitive\":[\"rgb(0, 102, 204)\",\"rgb(204, 0, 0)\"],\"afterJs\":[\"rgb(1, 2, 3)\",\"rgb(200, 100, 0)\"],\"dark\":\"rgb(102, 178, 255)\"}\nall assertions passed\n\nRead it as: scoped shows the override reaching the child span; otherCard shows it not reaching the span in the other card; bad is the inherited black (the invalid var() became unset) while literal stays red; mq is the plain rule's colour because the media rule with var() never applied; afterJs shows the JS update reaching #a but not the self-declaring #b; dark shows the attribute flip. Changing the media condition to a literal 0px makes the mq assertion throw (the colour becomes rgb(1, 2, 3) where rgb(9, 9, 9) is expected), and deleting the [data-theme=\"dark\"] rule makes the dark assertion throw (the colour stays rgb(0, 102, 204) where rgb(102, 178, 255) is expected).\n\nPitfalls\n\nCustom properties are inherited by default, so a value set high in the tree reaches everything below; scope deliberately.\nA typo in the name gives a silent fallback or unset, not an error. Always give fallbacks for optional hooks.\n\nRunning the code\n\nnpm init -y && npm i playwright@1.48.2 # inside mcr.microsoft.com/playwright:v1.48.2-jammy\nadd \"type\": \"module\" to package.json, save the test as css-vars.mjs\nnode css-vars.mjs\nSass sample, in a node:22 container: npx -y sass@1.77.8 in.scss"}},{"@type":"Question","name":"A layout looks correct in Chrome DevTools responsive mode, but on a real iPhone the header overlaps content when the browser chrome changes height and a sticky footer jumps unexpectedly. How would you debug and fix this class of responsive bugs?","acceptedAnswer":{"@type":"Answer","text":"How I would debug it\nI would reproduce the bug on a physical iPhone first, because Chrome responsive mode does not fully match Safari's viewport behavior. One note on terminology before going further: \"browser chrome\" below means the address bar, tabs, and other on-screen browser UI that can expand or collapse, not the Chrome browser itself; the two meanings of \"chrome\" are unrelated. Then I would inspect computed heights, scroll containers, and any element using 100vh, position: sticky, or position: fixed.\n\nLikely causes\n100vh on iOS can behave differently when the browser chrome expands or collapses\nA sticky or fixed footer may ignore safe-area insets\nA parent container may have overflow rules that interfere with sticky positioning\n\nFix strategy\nReplace 100vh with 100dvh (dynamic viewport height: unlike the static 100vh, it updates automatically as the browser chrome shows or hides) when I need the visible viewport height\nUse env(safe-area-inset-bottom) (a safe area is the part of the screen not covered by a device's notch, home indicator, or rounded corners) for footer spacing on notch devices\nAvoid tying layout math to the old static viewport height if the browser UI changes size\nTest with the address bar visible and hidden to catch jumpy behavior\n\nExample fallback\nIf a browser does not handle dynamic viewport units consistently, I may use a small JavaScript fallback to set an app height variable from window.innerHeight. The key is to keep the layout stable across scroll and chrome transitions, then verify on Safari, not just in DevTools."}},{"@type":"Question","name":"How do you stay informed about what a function you regularly work with actually cares about and is measured on, even when you're not in the room for their planning?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nBuild a standing information diet from what the partner function already produces for itself, its goals or planning document, the metrics it is measured on, and its retro or release notes, and pair that with a recurring informal check-in with one counterpart in that function. You are not trying to get invited into their planning meeting; you are trying to read what they optimize for, and occasionally confirm your read against a real person.\n\nStructured elaboration\n\nChannel | Typical cadence | What it surfaces\n\nTheir goals or planning document (OKRs, roadmap) | Once per planning cycle | What they are formally accountable for this period\nDashboards or metrics they report on | Check periodically | What \"good\" looks like for them, in their own numbers\nRetro notes, release notes, postmortems | As published | What is currently painful or top of mind for them\nRecurring 1:1 with one counterpart | Biweekly or monthly | Informal context, upcoming priorities, translation of jargon\nOccasional silent sit-in on their planning | A couple of times a year | Calibrates your read of the artifacts against how they actually talk about trade-offs\n\nThe habit that ties these together: translate their metric into one sentence you could say back to them and have them agree it is accurate, then test that sentence the next time you talk. If you cannot state their current priority in a sentence they would sign off on, your information diet has a gap.\n\nWorked example\n\nSuppose you regularly partner with a support or customer-success function but are not in their planning. Their quarterly goals page (a document they publish for their own team) states the goal is \"reduce median response time.\" Reading that before proposing a change that would meaningfully increase inbound volume lets you flag the likely trade-off to your counterpart ahead of launch, rather than finding out after the fact that you worked against their stated goal. The artifact told you what they were measured on; the counterpart conversation confirmed it was still current.\n\nTrade-offs & pitfalls\n\nRelying only on artifacts risks reading a goal that is stale or aspirational and no longer reflects what the team is actually prioritizing day to day.\nRelying only on a single counterpart's opinion risks mistaking one person's take for the function's actual priority, especially if that person is not close to how the team's metrics are reviewed.\nA common miss: reading the dashboard but never validating the interpretation with anyone in that function, which produces confidently wrong assumptions that only surface when a decision already went the wrong way.\nThe senior differentiator on an easy-sounding question like this is treating it as a standing habit built before you need it, rather than something you scramble to learn only after a conflict has already surfaced."}},{"@type":"Question","name":"You need a draggable list that works with a mouse and on touchscreens. Compare using the native HTML5 drag-and-drop API with building it on pointer events, and say which you would choose and why.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nBuild it on pointer events. The native HTML5 drag-and-drop API (the draggable attribute plus the dragstart, dragover and drop events) is shorter to write for a mouse, but it ties you to the browser's drag session (the browser-owned state machine that runs from dragstart to drop, during which your page does not receive normal mouse or pointer move events), gives you little control over how the drag looks and behaves, and in a Chromium run with a simulated finger it never started a drag at all (output below). A list that must work with a mouse and on touchscreens needs one code path for all input, which is what pointer events (pointerdown, pointermove, pointerup, one event shape for mouse, pen and finger) provide. Keep the native API for the cases only it can do: dragging files or text in from outside the page, or between windows.\n\nWhat each approach gives you\n\nConcern | Native drag-and-drop | Pointer events\n\nMouse | Works: dragstart then drop | Works: you track the move yourself\nFinger | Did not fire dragstart in the Chromium run below | Same code as the mouse (pointerType, the property naming the device, is \"touch\")\nDrag preview | The browser draws a translucent snapshot; customising it is limited (setDragImage swaps in another image or element for the snapshot) | You move the real element or your own clone with transform, so any visual is possible\nDrop target detection | Browser fires dragenter / dragover / drop on targets | You work it out: document.elementFromPoint(x, y) (returns the topmost element at those viewport coordinates) or geometry\nData model | dataTransfer (the object on drag events that carries the payload as strings or files; effectAllowed on it states which operations such as move or copy are permitted), can cross windows and come from the OS | Plain JavaScript variables, same page only\nAuto-scroll near an edge | Left to the browser | You write it, so you control speed and edges\nKeyboard | None built in | None built in: both need a separate keyboard path\nCancel with Escape | Browser handles it | You handle pointercancel and keydown\n\nTwo details of the native API cause most bugs: drop never fires unless a dragover handler calls preventDefault(), and the drag is a browser-owned session, so what the user sees while dragging is mostly out of your hands.\n\nThe two lists, run side by side\n\nThe harness runs the pointer list on a plain mental model: the dragged row is moved in the DOM whenever the pointer is over a different row. Both lists are three rows (A, B, C). The gesture picks up A and releases over C, so a correct result is the order bca. The harness runs the mouse gesture in Chromium, Firefox and WebKit (Playwright's WebKit build, which is not Safari on iOS), then the same gesture with a simulated finger in Chromium:\n\nimport { chromium, firefox, webkit } from 'playwright';\n\nconst items =
    • A
    • B
    • C
    ;\nconst css = ``;\n\n// Native HTML5 drag and drop: reorder on drop.\nconst nativePage = css + items + ``;\n\n// Pointer-event reorder: one code path for mouse, pen and finger.\nconst pointerPage = css + items + ``;\n\nconst order = page => page.evaluate(() => [...list.children].map(li => li.dataset.id).join(''));\nconst rowY = n => 20 + 40 * n; // vertical centre of row n (0-based)\n\nasync function mouseDrag(page) { // pick up row A, drop on row C\n await page.mouse.move(50, rowY(0));\n await page.mouse.down();\n await page.mouse.move(50, rowY(1), { steps: 5 });\n await page.mouse.move(50, rowY(2), { steps: 5 });\n await page.mouse.up();\n}\nasync function mouseDragUp(page) { // pick up row C, drop on row A (upward)\n await page.mouse.move(50, rowY(2));\n await page.mouse.down();\n await page.mouse.move(50, rowY(1), { steps: 5 });\n await page.mouse.move(50, rowY(0), { steps: 5 });\n await page.mouse.up();\n}\nasync function fingerDrag(ctx, page) { // same gesture with a simulated touch (Chromium only)\n const cdp = await ctx.newCDPSession(page);\n const send = (type, y) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: type === 'touchEnd' ? [] : [{ x: 50, y }] });\n await send('touchStart', rowY(0));\n for (let y = rowY(0); y <= rowY(2); y += 10) { await send('touchMove', y); await page.waitForTimeout(16); }\n await send('touchEnd', rowY(2));\n await page.waitForTimeout(300);\n}\n\nfor (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {\n for (const [label, html] of [['native', nativePage], ['pointer', pointerPage]]) {\n const browser = await type.launch();\n const page = await browser.newPage();\n await page.setContent(html);\n await mouseDrag(page);\n await page.waitForFunction(() => events.includes('drop'), null, { timeout: 3000 }).catch(() => {});\n console.log(${name.padEnd(8)} mouse ${label.padEnd(7)} order=${await order(page)} events=${await page.evaluate(() => events.join(','))});\n await browser.close();\n }\n}\n\nfor (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {\n const browser = await type.launch();\n const page = await browser.newPage();\n await page.setContent(pointerPage);\n await mouseDragUp(page);\n await page.waitForFunction(() => events.includes('drop'), null, { timeout: 3000 }).catch(() => {});\n const up = await order(page);\n console.log(${name.padEnd(8)} mouse pointer upward (C onto A) order=${up});\n if (up !== 'cab') { console.log('FAIL'); process.exitCode = 1; } // a one-directional insert would give acb\n await browser.close();\n}\n\nfor (const [label, html] of [['native', nativePage], ['pointer', pointerPage]]) {\n const browser = await chromium.launch();\n const ctx = await browser.newContext({ hasTouch: true });\n const page = await ctx.newPage();\n await page.setContent(html);\n await fingerDrag(ctx, page);\n console.log(chromium finger ${label.padEnd(7)} order=${await order(page)} events=${await page.evaluate(() => events.join(','))});\n await browser.close();\n}\n\nTwo lines of the pointer handler are not obvious. dragged.compareDocumentPosition(over) returns a bitmask (a number whose individual bits are separate yes/no flags); & Node.DOCUMENT_POSITION_FOLLOWING keeps only the bit that means \"over comes after dragged in the document\", so after is truthy when the pointer is over a row below the dragged one. overafter ? 'after' : 'before' then calls over.after(dragged) or over.before(dragged), which moves the dragged row to the far side of the row under the pointer, so the dragged row always travels in the direction of the pointer.\n\nTraced for the mouse gesture (rows are 41 px tall, the 40 px height plus a 1 px bottom border, so row n spans y = 41n to 41n + 41; the mouse goes from y = 20 down to 60 in five steps of 8 px, then on to 100 the same way):\n\nPointer y | Row under it | Action | DOM order\n\n20 to 36 | A (the dragged row) | nothing, over === dragged | abc\n44 | B | B follows A, so B.after(A) | bac\n52 to 76 | A again, now in the middle | nothing | bac\n84 | C | C follows A, so C.after(A) | bca\n92 to 100 | A again, now at the bottom | nothing | bca\n\npointerup then logs drop, which is why the final order is bca.\n\nThe downward trace never takes the 'before' branch, so a third gesture covers it: on a fresh pointer list in each engine, the script picks up C and drops it on A, and expects cab. It sets a non-zero exit code on any other order. If the ternary is replaced with over.after(dragged), the script prints acb and FAIL.\n\nPrinted output (the same on 10 consecutive runs; the script exits 0):\n\nchromium mouse native order=bca events=dragstart,drop\nchromium mouse pointer order=bca events=pointerdown:mouse,drop\nfirefox mouse native order=bca events=dragstart,drop\nfirefox mouse pointer order=bca events=pointerdown:mouse,drop\nwebkit mouse native order=bca events=dragstart,drop\nwebkit mouse pointer order=bca events=pointerdown:mouse,drop\nchromium mouse pointer upward (C onto A) order=cab\nfirefox mouse pointer upward (C onto A) order=cab\nwebkit mouse pointer upward (C onto A) order=cab\nchromium finger native order=abc events=\nchromium finger pointer order=bca events=pointerdown:touch,drop\n\nWith a mouse, both approaches reorder correctly in all three engines. With a simulated finger (DevTools Protocol touch events) the pointer-event list reorders and the native list receives no dragstart and does not change. That result comes from desktop Chromium with synthetic touch, not from a phone, so treat it as a demonstration of the difference in event models. Mobile browsers have their own rules for starting a native drag, so test the native route on real devices before depending on it.\n\nWhy pointer events win here, and what it costs\n\nThe decision rests on the stated requirement, \"mouse and touchscreens\". With pointer events there is one handler set to test and maintain, touch-action: none on the drag handle makes the browser hand the finger gesture to your code instead of scrolling (without it the browser may claim the gesture for scrolling and fire pointercancel), and setPointerCapture keeps events flowing when the pointer leaves the element. The cost is that you now own:\n\n1. Hit testing: which row is under the pointer (the harness uses elementFromPoint).\n2. The visual: a lifted clone or a transform on the dragged row, plus a placeholder gap.\n3. Auto-scroll when the pointer nears a scrolling container's edge, driven by requestAnimationFrame.\n4. Accessibility: neither API is keyboard operable by itself, so a keyboard reorder path (for example Space to pick up, arrow keys to move, Space to drop) and a live-region announcement (text placed in an element with aria-live, which a screen reader reads aloud when it changes, for example \"A moved to position 3\") are needed whichever you pick.\n\nWhat would flip the decision\n\nDropping files from the desktop, or dragging text or links between windows or tabs: only the native dataTransfer crosses those boundaries. Use native events for the file drop zone and pointer events for the internal reorder.\nA mouse-only internal admin tool with a deadline: the native API is the least code and works on every desktop engine in the table above.\nA library such as one built on pointer events already in the project: reuse it rather than rewriting the four items above.\n\nPitfalls\n\nSetting draggable=\"true\" on rows of a pointer-based list: the browser then starts its own drag session and competes with your handlers.\nForgetting touch-action: none on the handle, then wondering why a finger drag turns into a page scroll.\nReordering the DOM on every pointermove without checking the position changed, which makes rows flicker and wastes layout work.\n\nRunning the code\n\nmkdir demo && cd demo && echo '{\"type\":\"module\"}' > package.json\nnpm i playwright@1.48.2\nsave the listing above as dnd-compare.mjs\ndocker run --rm -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy node dnd-compare.mjs\n\nThe container ships Chromium, Firefox and WebKit builds matching Playwright 1.48.2."}},{"@type":"Question","name":"What is the difference between 'culture fit' and 'culture add', and which do you think better describes you as a candidate? Give one concrete example of a perspective, skill, or way of working you would bring to a team that is not already well represented there.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nCulture fit asks whether you already share a team's existing norms and behaviors; culture add asks what you would bring that the team does not already have. I would describe myself mostly as a culture add: I share the fundamentals a team needs to trust me (reliability, candor, respect for other people's time), but the useful thing I offer beyond that is a genuinely different working background rather than a mirror of the team that is already there.\n\nStructured elaboration\n1. Define both terms precisely before answering for yourself. Culture fit is about alignment on shared behaviors and values: does this person operate the way we already operate. Culture add is about complementary difference: does this person's background, working style, or perspective fill a gap the team doesn't currently have.\n2. Explain why the distinction matters, not just define it. A team optimized purely for fit tends toward groupthink: everyone reasons the same way, so blind spots go unchallenged and the same kinds of mistakes recur. A team that only adds without any shared fit becomes uncoordinated: people can't predict each other's reasoning enough to move fast together. The healthy target is fit on a small number of load-bearing behaviors (honesty, follow-through, respect) plus deliberate add on everything else.\n3. Give a genuine, specific example of your own add, not a generic trait. Vague claims (\"I bring diverse perspectives\") are the single most common failure mode here; a strong answer names the concrete gap and the concrete evidence.\n4. Anticipate the natural follow-up: how do you know your difference is actually useful, versus just different for its own sake. The answer is to point at a specific decision, disagreement, or piece of feedback that changed because of the difference you brought, not just a credential or background fact.\n\nWorked example\nSuppose your last two teams were both product engineering teams building consumer-facing features, and the team you're interviewing for is mostly staffed by engineers with that same background. Your own prior role was on a data-platform team, closer to the systems that feed those consumer features than to the features themselves. A concrete add-story: in a past project, a product team wanted to ship a new recommendation feature quickly; because of your platform background, you asked a question the rest of the team hadn't raised (whether the upstream data pipeline's freshness guarantees actually matched what the feature's UI implied to users), which surfaced a real gap between a 24-hour batch refresh and a UI copy that said \"updated just for you.\" The team fixed the copy and adjusted the refresh cadence before launch rather than after a user complaint. That is a genuine add: a different background produced a question the existing team composition was less likely to ask on its own, and it changed a real outcome.\n\nTrade-offs & pitfalls\nThe common failure is answering only the definitional half (correctly explaining fit versus add) and then, when asked for a personal example, retreating to generic self-description (\"I'm a good communicator\", \"I care about quality\") that any candidate could say and that does not actually demonstrate difference. A second pitfall is overcorrecting into implying you don't fit at all; the strongest answers are explicit that you also share the small set of behaviors every functioning team needs, and that add is about everything on top of that baseline, not a replacement for it."}},{"@type":"Question","name":"An effect sets state that is also in its own dependency list, and the page freezes. Reproduce the loop in a few lines and walk through how you would break it, saying when each fix is appropriate.","acceptedAnswer":{"@type":"Answer","text":"An effect is a function React runs after it has drawn a render, and its dependency list is the set of values that decides whether it runs again. If the effect sets a piece of state that is also in that list, every run causes a new render, the new render changes the dependency, and the effect runs again, forever. To break the loop, first decide what the effect was supposed to do, because the right fix depends on that: delete the effect, move the work into an event handler, compute the value during render, change what the list contains, or make the state update a no-op when nothing changed.\n\nReproducing the loop in a few lines\n\nfunction SelfCount() {\n const [n, setN] = useState(0);\n useEffect(() => {\n setN(n + 1); // changes n ...\n }, [n]); // ... which is the dependency, so the effect runs again\n return

    n={n}

    ;\n}\n\nReact compares each dependency with the previous render's value using Object.is (a strict \"same value\" check: two different objects or arrays are never equal, even if their contents match). n goes from 0 to 1, so the effect runs again, sets 2, and so on. The same loop appears in two less obvious shapes, which the runnable demo below reproduces:\n\nAn object or array created during render in the list. const options = { q } is a new object on every render, so [options] always \"changed\", and an effect that sets state therefore re-renders and re-creates options.\nAn effect that writes a freshly built copy of the state it watches. setItems(items.filter(...)) returns a new array even when nothing was removed, so [items] changes on every run.\n\nBreaking the loop: which fix fits which intent\n\nWhat the effect was meant to do | Fix | Why it is correct\n\nRun once to initialise something | Empty list [], and use an updater setN(v => v + 1) | Nothing in the list can change. An updater is the function form of the setter: React calls it with the latest queued state, so the code does not need to read n from the closure (the snapshot of variables that one render's function captured)\nReact to a user action (a click, a submit) | Delete the effect, do the work in the event handler | The cause is the event, not the render. No dependency to get wrong\nCompute a value from props or state | Delete the effect and the state, compute during render (useMemo if costly) | The value cannot drift out of sync with its inputs, and there is no extra render\nRe-run when a value changes, where the list holds an object or function | Depend on the primitives inside it ([q]), or stabilise the object with useMemo | Equality is checked on values that only change when they really change\nNormalise or clean state that must stay in state | Functional update that returns the previous array/object when nothing changed | React bails out (stops early and skips re-rendering the component's children) when the new state is identical to the current one, so the cycle ends\nSynchronise with something outside React (a fetch, a subscription) | Keep the effect, but keep the state it writes out of its own list | The list should name what the effect reads from the outside world, not what it writes\n\nThe react.dev guide says: \"When something can be calculated from the existing props or state, don't put it in state. Instead, calculate it during rendering.\" On the equal-value rule, the useState reference says: \"If the new value you provide is identical to the current state, as determined by an Object.is comparison, React will skip re-rendering the component and its children.\"\n\nRemoving a dependency from the list just to stop the loop is the wrong move when the effect really reads that value: the effect then uses a stale value (a copy captured by an earlier render: an effect that read n as 0 keeps reading 0 after the state has moved on), and the hook lint rules in eslint-plugin-react-hooks will flag it. Use an updater, restructure, or move the work, and keep the list honest.\n\nWorked example: nine components, one counter\n\nThe demo renders each broken and fixed version under jsdom (a simulated browser in Node) and counts renders with a plain counter. The broken versions contain a safety valve that stops them at 25 renders so the script finishes instead of freezing. Each broken case asserts that the valve was hit. The four fixed components that still run an effect (InitOnce, ObjDepPrimitive, ObjDepMemo, PruneGuarded) carry the same valve and assert that it was not hit, so a fix that stops working fails an assertion instead of freezing the script. ClickCount and PruneDerived have no effect, so they have no valve; the demo asserts their render counts instead.\n\nThe first eleven lines of the listing (up to the Testing Library import) are environment setup, not part of the technique. JSDOM builds a fake browser page; the next three lines expose its window, document and navigator as globals that React and Testing Library look for; IS_REACT_ACT_ENVIRONMENT = true tells React that updates are wrapped in act(), the test helper that makes React finish pending state updates and effects before returning, which Testing Library's render does for you. The unused names pulled out of React and Testing Library are never used and can be ignored.\n\nThe nine components pair up as follows:\n\nSelfCount is the loop; InitOnce makes the same effect run once, and ClickCount moves the increment into the click handler.\nObjDep puts a fresh object in the list; ObjDepPrimitive lists the string q instead, and ObjDepMemo keeps the object but only rebuilds it when q changes.\nPrune writes a new array on every run; PruneGuarded returns the old array when nothing was removed, and PruneDerived has no effect and no extra state.\n\n// effect-loop.mjs\nimport { JSDOM } from 'jsdom';\nimport assert from 'node:assert/strict';\nconst dom = new JSDOM('', { url: 'http://localhost/' });\nglobalThis.window = dom.window;\nglobalThis.document = dom.window.document;\nObject.defineProperty(globalThis, 'navigator', { value: dom.window.navigator });\nglobalThis.IS_REACT_ACT_ENVIRONMENT = true;\nconst React = (await import('react')).default;\nconst { useState, useEffect, useMemo, useCallback, useRef, memo, useReducer } = React;\nconst { render, screen, fireEvent, cleanup, act, waitFor } = await import('@testing-library/react');\nconst h = React.createElement;\n\nconst CAP = 25; // safety valve so the demo ends instead of freezing the tab\n\nfunction makeCounter() {\n return { renders: 0, runaway: false };\n}\n\n// Case 1: the effect sets the state that is in its own dependency list.\nfunction SelfCount({ c }) {\n const [n, setN] = useState(0);\n c.renders++;\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve\n setN(n + 1);\n }, [n]);\n return h('p', null, 'n=' + n);\n}\n// Fix 1a: the intent was \"initialise once on mount\": empty list plus an updater.\nfunction InitOnce({ c }) {\n const [n, setN] = useState(0);\n c.renders++;\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve\n setN((v) => v + 1);\n }, []);\n return h('p', null, 'n=' + n);\n}\n// Fix 1b: the intent was \"count clicks\": the work belongs in the handler.\nfunction ClickCount({ c }) {\n const [n, setN] = useState(0);\n c.renders++;\n return h('button', { onClick: () => setN(n + 1) }, 'n=' + n);\n}\n\n// Case 2: an object literal built during render is in the dependency list.\nfunction runSearch(o) { return ['hit:' + o.q]; }\nfunction ObjDep({ c, q }) {\n const [results, setResults] = useState([]);\n c.renders++;\n const options = { q };\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; }\n setResults(runSearch(options));\n }, [options]);\n return h('p', null, results.join(','));\n}\nfunction ObjDepPrimitive({ c, q }) {\n const [results, setResults] = useState([]);\n c.renders++;\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve\n setResults(runSearch({ q }));\n }, [q]);\n return h('p', null, results.join(','));\n}\nfunction ObjDepMemo({ c, q }) {\n const [results, setResults] = useState([]);\n c.renders++;\n const options = useMemo(() => ({ q }), [q]);\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve\n setResults(runSearch(options));\n }, [options]);\n return h('p', null, results.join(','));\n}\n\n// Case 3: the effect writes a fresh array derived from the state it watches.\nfunction Prune({ c }) {\n const [items, setItems] = useState([3, 1, 2]);\n c.renders++;\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; }\n setItems(items.filter((x) => x > 0)); // new array even when nothing is removed\n }, [items]);\n return h('p', null, items.join(','));\n}\nfunction PruneGuarded({ c }) {\n const [items, setItems] = useState([3, 1, 2]);\n c.renders++;\n useEffect(() => {\n if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve\n setItems((prev) => {\n const next = prev.filter((x) => x > 0);\n return next.length === prev.length ? prev : next; // same reference: React bails out\n });\n }, [items]);\n return h('p', null, items.join(','));\n}\nfunction PruneDerived({ c }) {\n const [items] = useState([3, 1, 2]);\n c.renders++;\n const visible = useMemo(() => items.filter((x) => x > 0), [items]);\n return h('p', null, visible.join(','));\n}\n\nfunction run(label, Comp, props = {}) {\n const c = makeCounter();\n const view = render(h(Comp, { c, ...props }));\n const out = { label, renders: c.renders, runaway: c.runaway };\n console.log(JSON.stringify(out));\n return { c, view };\n}\n\nlet r;\nr = run('1 broken self-count', SelfCount);\nassert.equal(r.c.runaway, true); assert.ok(r.c.renders >= CAP); cleanup();\n\nr = run('1a init once', InitOnce);\nassert.equal(r.c.runaway, false); assert.equal(r.c.renders, 2); cleanup();\n\nr = run('1b handler', ClickCount);\nassert.equal(r.c.renders, 1);\nfireEvent.click(screen.getByRole('button'));\nconsole.log(JSON.stringify({ label: '1b after click', renders: r.c.renders }));\nassert.equal(r.c.renders, 2); cleanup();\n\nr = run('2 broken object dep', ObjDep, { q: 'a' });\nassert.equal(r.c.runaway, true); cleanup();\n\nr = run('2a primitive dep', ObjDepPrimitive, { q: 'a' });\nassert.equal(r.c.renders, 2); assert.equal(r.c.runaway, false); cleanup();\n\nr = run('2b useMemo dep', ObjDepMemo, { q: 'a' });\nassert.equal(r.c.renders, 2); assert.equal(r.c.runaway, false); cleanup();\n\nr = run('3 broken prune', Prune);\nassert.equal(r.c.runaway, true); cleanup();\n\nr = run('3a guarded updater', PruneGuarded);\nconst guardedRenders = r.c.renders;\nassert.ok(guardedRenders <= 2, 'bounded'); assert.equal(r.c.runaway, false); cleanup();\n\nr = run('3b derived in render', PruneDerived);\nassert.equal(r.c.renders, 1);\nassert.equal(screen.getByText('3,1,2') !== null, true);\nconsole.log('all assertions passed');\n\nRun in a node:22 container (Node 22.23.3), it prints:\n\n{\"label\":\"1 broken self-count\",\"renders\":25,\"runaway\":true}\n{\"label\":\"1a init once\",\"renders\":2,\"runaway\":false}\n{\"label\":\"1b handler\",\"renders\":1,\"runaway\":false}\n{\"label\":\"1b after click\",\"renders\":2}\n{\"label\":\"2 broken object dep\",\"renders\":25,\"runaway\":true}\n{\"label\":\"2a primitive dep\",\"renders\":2,\"runaway\":false}\n{\"label\":\"2b useMemo dep\",\"renders\":2,\"runaway\":false}\n{\"label\":\"3 broken prune\",\"renders\":25,\"runaway\":true}\n{\"label\":\"3a guarded updater\",\"renders\":1,\"runaway\":false}\n{\"label\":\"3b derived in render\",\"renders\":1,\"runaway\":false}\nall assertions passed\n\nReading the output: the three broken components reach the 25-render valve. The initialise-once version and the primitive-dependency version settle at 2 renders (the first render plus one update from the effect). The click handler version stays at 1 render until the click and then goes to 2. The derived value stays at 1 render, because no effect runs at all. The guarded updater also showed 1 render in this run; the useState docs warn that React may sometimes call the component once more before bailing out, so treat 1 to 2 as the expected range and the loop being gone as the guarantee.\n\nTrade-offs and pitfalls\n\nDeleting the effect is the best fix more often than not, because the effect only existed to copy one value into state after rendering. The \"derived state in an effect\" pattern costs an extra render even when it does not loop.\nuseMemo for an object dependency is a fix for the identity problem only. If the memo's own inputs are new objects every render, it is memoizing nothing.\nA guard such as if (n < 10) setN(n + 1) stops the freeze but leaves a render cascade, and it hides the design problem. Use it only when the cascade is the intended behaviour.\nFetch effects that set state with the response need a different protection (ignore stale responses, cancel on cleanup). The dependency list is still the place to look first when the page spins.\nIn the browser, find the culprit with the React DevTools Profiler (a recorded session shows the same component committing again and again; a commit is the step where React writes a finished render into the page, and the Profiler lists one per update).\n\nRunning the code\n\nmkdir loop && cd loop && printf '{\"type\":\"module\"}' > package.json\nnpm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16.0.1 @testing-library/dom@10.4.0 jsdom@25.0.1\nnode effect-loop.mjs # the listing above"}},{"@type":"Question","name":"Describe a time you mentored someone from their first day through shipping their first piece of real work. How did you ramp them up?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nRamping someone from day one to their first shipped work is a deliberate sequence, not a single onboarding checklist: assess what they actually already know, give them small real tasks with tight review loops before a full feature, gradually widen the scope of ownership, and define upfront what \"shipped\" and \"done\" mean so the finish line is unambiguous. The plan should look different depending on who's arriving, not just be a fixed template applied to everyone.\n\nStructured elaboration\n\nThe default arc\nFirst few days: orient and assess. Don't assume a blank slate; find out what they already know so you're not re-teaching things or, worse, skipping things they actually need.\nEarly tasks: small, real, low-blast-radius work with fast, close review. The goal here is confidence and calibration to the team's standards, not speed.\nMiddle stretch: progressively larger scope with more independence, review shifting from \"check everything\" to \"check the risky parts.\"\nFirst real shipped piece: something end-to-end they own, with you available but not doing it alongside them, and a clear definition of \"done\" agreed before they start, so success isn't a moving target.\n\nAdapting the plan to who's actually arriving\nThis is where a generic checklist breaks down, and it's the part that separates a senior answer:\nA contractor under least-privilege or compliance constraints: access is scoped down from day one, so the plan has to work around what they legitimately can't see or touch, and documentation often needs to be more explicit since they can't casually ask around as easily as a full-time hire embedded in the org.\nA career-changer from an adjacent discipline (a backend engineer moving into data engineering, a research scientist moving into production ML): they're not a blank slate, they have real transferable skills. The plan should explicitly identify what carries over and target ramp-up specifically at the actual new-domain gaps, not restart from zero the way you would for someone with no relevant background.\nA cohort of remote interns rather than one hire: 1:1 pairing time doesn't scale to a group. The plan shifts toward a shared structured curriculum, peer learning between the interns, and scheduled office hours, with 1:1 time reserved for the things that genuinely need it.\nA remote hire versus a senior IC joining: a remote hire needs more of everything written down explicitly, since the informal hallway learning that fills gaps for an in-person hire doesn't happen by accident. A senior IC's gap is usually organizational context and relationships, not raw skill, so their plan should be lighter on procedural scaffolding and heavier on introductions, context on how decisions get made, and where the landmines are.\n\nWorked example\n\nSituation\nI mentored someone joining as an individual contributor with solid general skills but no exposure to our specific stack or codebase, with a goal of them shipping one real, complete piece of work within their first several weeks.\n\nAction\nWeek one was mostly orientation and a short assessment task to see where they actually stood, not a generic reading list. From there, I gave them a small real bug fix with a tight review loop so they got fast, specific feedback on our conventions early, before those habits calcified the wrong way. Over the following weeks the scope widened: a small self-contained feature with me reviewing closely, then a larger piece with me available but stepping back from line-by-line review, focusing instead on the riskiest parts of the design.\n\nResult\nThey shipped a real, complete piece of work end-to-end within the target window, with a review pass that looked much closer to how we review any other team member's work by that point, which was the actual signal of readiness, not just that the calendar had passed.\n\nTrade-offs & pitfalls\n\nTreating every new hire's plan as the same template. A junior mentor runs the same onboarding for a contractor, a career-changer, an intern cohort, and a senior IC. A senior mentor adapts the shape of the plan to who's actually arriving, because the actual gap being closed is different in each case.\nUnder-scoping early tasks out of excessive caution, or over-scoping out of impatience. Both undermine the confidence-building purpose of the early stretch: too small and it's condescending or boring; too large too soon and the first review becomes overwhelming and demoralizing.\nNot defining \"done\" up front. Ambiguity about what counts as finished either causes needless rework or lets something ship that isn't actually ready, and both erode trust in the mentoring relationship.\nIgnoring the constraints a nontraditional hire is actually operating under. Applying a full-access, in-person, junior-IC plan to a least-privilege contractor or a remote hire sets them up to fail on logistics that have nothing to do with their actual skill."}},{"@type":"Question","name":"Some problems are not phrased as 'search this array' but still have a monotonic answer space: for example, given job sizes and a fixed number of identical servers, find the minimum possible value of the maximum load per server; or, given positions along a line, place k markers to maximize the minimum distance between any two. Explain how you recognize that binary search applies here even though there is no sorted array to search.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nBinary search doesn't require a sorted array; it only requires a monotonic predicate over the answer space, meaning that as candidate answers are scanned in one direction, the predicate flips from false to true (or true to false) exactly once. Once a fast \"is this candidate value feasible\" check exists with that monotonic property, the search runs directly over the range of possible answers instead of over array indices.\n\nStructured elaboration\nApproach\nRecognizing the pattern: look for a question phrased as \"find the minimum or maximum value such that some condition holds,\" where checking the condition for one fixed candidate value is easier than finding the optimal value directly. If increasing the candidate value can only make the condition easier (or only harder) to satisfy, never both, the condition is monotonic and binary search applies.\nJob/server example: minimize the maximum load assigned to any of k identical servers, given a list of job sizes. For a candidate max-load D, checking feasibility means greedily assigning jobs to a server until adding the next job would exceed D, at which point a new server starts; if the assignment finishes using k or fewer servers, D is feasible. Feasibility is monotonic in D: any D' greater than a feasible D is also feasible, since a looser cap can only make greedy assignment use the same number of servers or fewer.\nMarker-placement example: place k markers along a line to maximize the minimum distance between any two chosen markers. For a candidate minimum distance D, checking feasibility means greedily placing markers left to right, always taking the next position at least D away from the last placed marker; if that produces k or more markers, D is feasible. Feasibility is monotonic in the opposite direction here: any D' smaller than a feasible D is also feasible, since a smaller required gap can only let you place the same number of markers or more.\nThe same recognize-the-monotonic-property instinct applies to the \"find peak element\" problem, where the array itself is not sorted at all, but comparing an element to one neighbor still tells you which half must contain a peak; \"is there a peak here or to one side\" is a property that binary search's halving can still exploit even though nothing about the array is globally ordered.\n\ndef max_min_load(job_sizes, num_servers):\n \"\"\"\n Minimum possible value of the maximum load on any server, splitting the\n jobs (in given order) into num_servers contiguous groups.\n \"\"\"\n def feasible(max_load):\n servers_used = 1\n current = 0\n for size in job_sizes:\n if current + size > max_load:\n servers_used += 1\n current = size\n if servers_used > num_servers:\n return False\n else:\n current += size\n return True\n\n lo, hi = max(job_sizes), sum(job_sizes)\n while lo < hi:\n mid = (lo + hi) // 2\n if feasible(mid):\n hi = mid\n else:\n lo = mid + 1\n return lo\n\ndef max_min_distance(positions, k):\n \"\"\"\n Place k markers among sorted positions to maximize the minimum distance\n between any two adjacent chosen markers.\n \"\"\"\n positions = sorted(positions)\n\n def can_place(min_dist):\n count, last = 1, positions[0]\n for p in positions[1:]:\n if p - last >= min_dist:\n count += 1\n last = p\n return count >= k\n\n lo, hi = 0, positions[-1] - positions[0]\n while lo < hi:\n mid = (lo + hi + 1) // 2 # bias up: looking for the largest feasible D\n if can_place(mid):\n lo = mid\n else:\n hi = mid - 1\n return lo\n\nKey points\nThe object binary search operates over is the candidate answer value, not an array index.\nProving the greedy feasibility check is monotonic, and separately proving that the greedy check itself is correct, are two distinct things to justify in an interview.\nThe search range's bounds come from the problem itself, for example [max single job size, sum of all job sizes] for the load-balancing version.\n\nWorked example\njob_sizes = [7, 2, 5, 10, 8], num_servers = 2. Binary search bounds: lo = max(job_sizes) = 10, hi = sum(job_sizes) = 32. Checking feasible(18): greedily accumulate 7, 2, 5 (running total 14); adding 10 would make 24 > 18, so a second server starts with 10, then 8 is added (running total 18, exactly at the cap). The assignment finishes using exactly 2 servers, so 18 is feasible. Checking feasible(17): the same greedy walk starts a third server once it reaches 8, exceeding the 2-server budget, so 17 is infeasible. Binary search converges on the smallest feasible value: max_min_load([7, 2, 5, 10, 8], 2) prints 18.\n\npositions = [1, 2, 4, 8, 9], k = 3: max_min_distance prints 3, matching a direct check that placing markers at 1, 4, 8 gives a minimum gap of 3, and no arrangement of 3 markers on these positions can do better than 3.\n\nTrade-offs & pitfalls\nComplexity\nTime: , where n is the number of jobs or positions (each feasibility check is ) and W is the width of the answer search range (sum of job sizes, or the max position minus the min position); is the number of binary-search iterations.\nSpace: extra beyond sorting, if sorting is needed (the marker-placement version needs the positions sorted first, a one-time cost).\n\nEdge cases\nk <= 1 for the marker-placement version: any single marker trivially satisfies any distance requirement, so the answer is unconstrained (commonly defined as 0 or unbounded, depending on the problem statement).\nnum_servers >= number of jobs: every job gets its own server, and the answer is just the largest single job.\nAll positions or job sizes equal: the feasibility checks degenerate but still behave correctly under the same greedy logic.\n\nThe hardest part of this pattern is proving the greedy feasibility check is actually correct, not just monotonic, which usually requires an exchange argument (showing any optimal solution can be rearranged into the greedy one without making it worse); stating \"binary search works because the answer space is monotonic\" without also justifying the O(n) check itself is an incomplete answer. A second common mistake is getting the search bounds wrong, either missing a valid answer at the boundary or introducing an off-by-one that causes the loop to terminate one step early or loop forever, depending on which bound is biased toward on a tie."}}]}

    Airbnb Frontend Engineer Interview Preparation Guide - Mid Level (2-5 Years)

    Frontend Developer
    Airbnb
    Mid Level
    6 rounds
    Updated 6/21/2026

    Airbnb's Frontend Engineer interview process consists of a recruiter screening, an online technical assessment featuring algorithmic problems, and a comprehensive virtual onsite known as the 'Engineering Loop.' The Engineering Loop comprises four distinct rounds evaluating coding proficiency, system design thinking, code review competency, and cultural alignment. For mid-level candidates, expect 4-6 weeks from initial application to offer, with emphasis on practical frontend problem-solving, architectural thinking, and user-centric design considerations. The process focuses on evaluating your ability to build scalable, performant, and accessible user interfaces while demonstrating clear communication and Airbnb's core values.

    Interview Rounds

    1

    Recruiter Screening

    2

    Online Technical Assessment

    3

    Coding/Algorithm Round (Onsite - Engineering Loop)

    4

    System Design Round (Onsite - Engineering Loop)

    5

    Code Review Round (Onsite - Engineering Loop)

    6

    Behavioral Round (Onsite - Engineering Loop)

    Frequently Asked Frontend Developer Interview Questions

    Frontend Performance and Rendering OptimizationHardTechnical
    102 practiced

    Your server-rendered React app passes a large initial state to the client and hydration dominates time to interactive. What would you change, and what does each option cost in complexity?

    Performance Trade-offs & Optimization StrategyMediumTechnical
    59 practiced

    Product wants the fastest possible improvement to page load time and gives you four weeks. You're weighing frontend work like lazy-loading and code-splitting against a backend API-aggregation effort. Which would you recommend starting with, and what would change your answer?

    Frontend Fundamentals: HTML, CSS, and Responsive StylingEasyTechnical
    81 practiced

    Explain CSS custom properties (variables): syntax, cascade and inheritance behavior, runtime updates via JavaScript, fallback values, and how they differ from preprocessor variables. Give examples where custom properties simplify theming and reduce duplication.

    Responsive, Multi-Platform, and Localized DesignMediumTechnical
    84 practiced

    A layout looks correct in Chrome DevTools responsive mode, but on a real iPhone the header overlaps content when the browser chrome changes height and a sticky footer jumps unexpectedly. How would you debug and fix this class of responsive bugs?

    Cross-Functional CollaborationEasyTechnical
    30 practiced

    How do you stay informed about what a function you regularly work with actually cares about and is measured on, even when you're not in the room for their planning?

    DOM Manipulation and Browser APIsMediumTechnical
    105 practiced

    You need a draggable list that works with a mouse and on touchscreens. Compare using the native HTML5 drag-and-drop API with building it on pointer events, and say which you would choose and why.

    Company Culture and Values FitMediumBehavioral
    71 practiced

    What is the difference between 'culture fit' and 'culture add', and which do you think better describes you as a candidate? Give one concrete example of a perspective, skill, or way of working you would bring to a team that is not already well represented there.

    Frontend Component and State ArchitectureMediumTechnical
    72 practiced

    An effect sets state that is also in its own dependency list, and the page freezes. Reproduce the loop in a few lines and walk through how you would break it, saying when each fix is appropriate.

    Mentoring and CoachingEasyBehavioral
    63 practiced

    Describe a time you mentored someone from their first day through shipping their first piece of real work. How did you ramp them up?

    Algorithmic Problem-Solving and Data Structure SelectionHardTechnical
    40 practiced

    Some problems are not phrased as 'search this array' but still have a monotonic answer space: for example, given job sizes and a fixed number of identical servers, find the minimum possible value of the maximum load per server; or, given positions along a line, place k markers to maximize the minimum distance between any two. Explain how you recognize that binary search applies here even though there is no sorted array to search.

    Want to create your own tailored preparation guide using our deep research?

    Get Started for Free

    Interview-Ready Courses

    Visual-first, interactive, structured learning paths

    Browse Frontend Developer jobs

    AI-enriched listings across hundreds of company career pages

    Explore Jobs