Spotify Frontend Developer (Entry Level) - Complete Interview Preparation Guide
Spotify's frontend developer interview process typically follows a structured funnel: an initial recruiter screening to assess background and motivation, followed by technical phone screens to evaluate core JavaScript and React fundamentals, and onsite interviews covering coding problems, frontend-specific technical depth, system design thinking appropriate for entry level, behavioral assessment aligned with Spotify's culture, and final interviewer round. The process is designed to assess problem-solving ability, familiarity with modern frontend tools and frameworks, code quality mindset, and cultural fit with Spotify's collaborative and product-focused environment.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with a Spotify recruiter to discuss your background, motivation for joining Spotify, understanding of the role, and logistics. This is a soft introduction to assess cultural fit and verify that your career goals align with the position. The recruiter will also confirm that you meet basic technical requirements and clarify any questions about the interview process, timeline, and role expectations.
Tips & Advice
Be authentic and enthusiastic about Spotify's mission and products. Research the company before the call—mention specific features or products you've used. Clearly articulate why you want to work in frontend development and why Spotify specifically. Ask thoughtful questions about team structure, growth opportunities, and the types of projects you'd work on. Keep answers concise and let the recruiter guide the conversation. Prepare a 2-3 minute elevator pitch about your background and why you're excited about this opportunity.
Focus Topics
Spotify Product and Tech Stack Familiarity
Demonstrate you've used Spotify, understand the product, and are aware of their technology (React, TypeScript, GCP).
Practice Interview
Study Questions
Communication and Professionalism
Communicate clearly, listen actively, and maintain professional demeanor. Show enthusiasm without overselling.
Practice Interview
Study Questions
Motivation and Career Goals
Clearly articulate your interest in frontend development and why Spotify appeals to you. Demonstrate knowledge of Spotify's product and mission.
Practice Interview
Study Questions
Technical Phone Screen - JavaScript Fundamentals
What to Expect
First technical assessment conducted over video call with an engineer. You'll discuss your technical background, review a coding problem focused on JavaScript fundamentals (likely arrays, strings, or object manipulation), and explain your approach and solution. The interviewer will assess your problem-solving approach, coding clarity, communication style, and foundational JavaScript knowledge. Expect questions about your past projects and how you debugged issues.
Tips & Advice
Use a shared coding environment (CoderPad, HackerRank, or similar). Write clean, readable code with meaningful variable names. Think aloud—explain your approach before coding. Ask clarifying questions about problem requirements. Test your code mentally with edge cases. If stuck, ask for hints or discuss your thought process rather than sitting silently. Optimize for readability first, then discuss optimization opportunities. Be prepared to discuss how you'd test this in a real scenario. Mention any relevant frontend libraries or tools if applicable to the problem.
Focus Topics
DOM Manipulation and Browser APIs
Understanding of DOM traversal, event handling, and common browser APIs. Knowledge of how JavaScript interacts with HTML and CSS.
Practice Interview
Study Questions
Communication and Code Clarity
Ability to explain your thought process, articulate assumptions, write readable code with clear variable names, and discuss trade-offs.
Practice Interview
Study Questions
Problem-Solving and Algorithmic Thinking
Ability to break down problems, identify patterns, think through edge cases, and develop efficient solutions. Approach problems methodically.
Practice Interview
Study Questions
JavaScript Fundamentals
Strong grasp of variables, functions, objects, arrays, closures, this keyword, async/await, promises, and ES6+ features. Ability to write clean, maintainable JavaScript code.
Practice Interview
Study Questions
Technical Phone Screen - React and Component Thinking
What to Expect
Second technical phone screen focused on React and modern frontend architecture. You'll solve a problem involving React component design, state management, or hooks. The interviewer will assess your understanding of React's component model, lifecycle, hooks (useState, useEffect), props, and how to structure component hierarchies. You may be asked to build a small component or discuss how you'd approach building a specific feature. This round also evaluates your familiarity with modern frontend tooling and TypeScript basics.
Tips & Advice
Think about component composition and reusability. Discuss why you'd structure components a certain way. Be prepared to explain the difference between controlled and uncontrolled components, and when to use each. Mention TypeScript types when appropriate—show you understand typing benefits. Discuss performance considerations like unnecessary re-renders, though don't over-optimize. If asked about state management, for entry level keep it simple (local state, props) but mention Redux or Zustand if experienced. Ask about edge cases and how you'd handle them. Code defensively—think about error handling and edge cases.
Focus Topics
Testing React Components
Familiarity with testing libraries like React Testing Library or Jest. Understanding of how to test component behavior, not implementation.
Practice Interview
Study Questions
TypeScript Basics
Understanding of basic TypeScript features: interfaces, types, generics, and how TypeScript improves code quality. Ability to write typed React components.
Practice Interview
Study Questions
React Hooks and State Management
Proficiency with hooks (useState, useEffect, useContext, useReducer). Understanding of side effects, cleanup, and dependency arrays. Basic knowledge of state management approaches.
Practice Interview
Study Questions
Component Architecture and Design
Ability to design reusable, maintainable components. Understanding of composition over inheritance, separation of concerns, and prop drilling. Knowledge of component patterns.
Practice Interview
Study Questions
React Fundamentals
Core understanding of components, JSX, props, state, and the component lifecycle. Knowledge of functional components and hooks (useState, useEffect, useContext).
Practice Interview
Study Questions
Onsite Interview - Coding and Component Development
What to Expect
First onsite round focused on practical coding and component development. You'll likely build a functional React component or feature within a time box (60-90 minutes). This might involve fetching data from an API, managing state, handling user interactions, and ensuring the component is responsive and accessible. You'll share your screen and code in real-time. The interviewer will assess code quality, your ability to ask clarifying questions, how you approach building user-facing features, and your testing mindset. Expect discussion about edge cases, error handling, and accessibility considerations.
Tips & Advice
Ask clarifying questions upfront—understand requirements fully before coding. Sketch out your approach on a virtual whiteboard before diving into code. Start with a basic working solution, then enhance it. Write clean code with clear variable names and comments. Handle edge cases (empty states, errors, loading states). Consider accessibility (ARIA labels, keyboard navigation, semantic HTML) as you code. Test your component mentally or with the browser console. Discuss trade-offs in your design choices. If you get stuck, think aloud and ask for guidance rather than silently debugging. Mention performance considerations but don't over-engineer for entry level. Show your debugging process if issues arise.
Focus Topics
Code Quality and Maintainability
Writing clean, readable code with meaningful names, comments, proper formatting, and avoiding code duplication. Structuring code for future maintainability.
Practice Interview
Study Questions
Responsive Design and CSS
Ability to build responsive layouts using CSS Flexbox, Grid, or styling libraries like Tailwind. Understanding of media queries and mobile-first design.
Practice Interview
Study Questions
Accessibility and User Experience
Awareness of WCAG guidelines, semantic HTML, ARIA labels, keyboard navigation, color contrast, and building inclusive user experiences.
Practice Interview
Study Questions
Error Handling and Edge Cases
Ability to anticipate and handle edge cases: empty states, loading states, error states, null/undefined values, and network failures gracefully.
Practice Interview
Study Questions
API Integration and Data Fetching
Understanding of fetching data from APIs using fetch or Axios, managing loading and error states, and handling asynchronous operations in React.
Practice Interview
Study Questions
Building Interactive React Components
Ability to build functional React components that handle state, side effects, and user interactions. Proficiency with hooks and component composition.
Practice Interview
Study Questions
Onsite Interview - Frontend System Design and Architecture
What to Expect
This round assesses your high-level thinking about frontend architecture and design decisions. You'll be asked questions like 'How would you structure a component for a music playlist?' or 'Design a checkout flow experience' or 'How would you handle state management for this feature?' This is not traditional system design (like backend architecture) but rather frontend-specific thinking about component hierarchies, data flow, performance considerations, and user experience trade-offs. The interviewer evaluates whether you think beyond individual components to consider the bigger picture—appropriate for entry level, this focuses on foundational thinking, not complex distributed systems.
Tips & Advice
Think out loud and sketch on whiteboard/virtual board. Ask clarifying questions about scale, user interactions, and constraints. Start simple and discuss how to evolve the design. Consider performance implications (bundle size, re-renders, lazy loading). Discuss separation of concerns and component boundaries. Mention libraries or patterns you'd use (Context API, custom hooks, etc.). For entry level, don't overcomplicate—focus on sensible, pragmatic design choices. Discuss accessibility and responsive design as part of your solution. Be open to feedback and discuss trade-offs. Relate examples to Spotify's product if possible (e.g., 'Like how Spotify's player needs to handle play/pause across routes, I'd consider...') to show product awareness.
Focus Topics
Handling Feature Complexity
Ability to break down complex features into manageable components and plan incremental implementation. Understanding of how to evolve simple designs.
Practice Interview
Study Questions
Performance Considerations
Awareness of code splitting, lazy loading, bundle optimization, avoiding unnecessary re-renders, and identifying performance bottlenecks. Basic knowledge of profiling tools.
Practice Interview
Study Questions
Data Flow and Props
Clear understanding of unidirectional data flow in React, passing data through props, and managing dependencies. Knowing when to lift state up.
Practice Interview
Study Questions
State Management Strategy
Understanding of when to use local state, props drilling, Context API, or other state management patterns. Ability to justify design choices based on complexity.
Practice Interview
Study Questions
Component Hierarchy and Composition
Ability to design logical component structures, determine component boundaries, and plan data flow between components. Understanding of parent-child relationships and composition patterns.
Practice Interview
Study Questions
Onsite Interview - Behavioral and Culture Fit
What to Expect
Final onsite round with a senior engineer or hiring manager focused on behavioral assessment and culture fit. This round evaluates your collaboration skills, learning agility, how you handle feedback, resilience, and alignment with Spotify's values. You'll be asked behavioral questions using the STAR method (Situation, Task, Action, Result). Typical questions cover: 'Tell me about a time you struggled with a technical problem and how you solved it,' 'Describe a situation where you had to learn something new quickly,' 'Tell me about your experience working in a team,' and 'How do you handle feedback?' The interviewer assesses whether you're someone colleagues want to work with, whether you're self-driven, and whether you align with Spotify's collaborative, product-focused culture.
Tips & Advice
Prepare 5-6 solid stories using the STAR method covering: learning quickly, overcoming technical challenges, collaboration, handling feedback, and initiative. Be specific with details—vague stories don't stand out. Focus on your role and learnings, not just the outcome. Show humility and growth mindset—it's okay to admit mistakes if you learned from them. Connect your stories to Spotify's values if possible. Ask thoughtful questions about team dynamics, mentorship, and company culture. Be authentic and personable—this is as much about team fit as competence. Discuss what excites you about working at Spotify and in frontend development. Show curiosity about the role and team.
Focus Topics
Initiative and Ownership
Willingness to take on challenges beyond assigned tasks, proactive problem-solving, and taking responsibility for outcomes. Demonstrate autonomy.
Practice Interview
Study Questions
Feedback and Self-Awareness
Ability to receive and act on feedback, self-reflect on weaknesses, and take ownership of growth. Demonstrate openness to improvement.
Practice Interview
Study Questions
Problem-Solving and Resilience
Approach to tackling difficult problems, resilience in face of challenges, ability to break down complex issues, and resourcefulness. Show persistence without giving up.
Practice Interview
Study Questions
Learning Agility and Growth Mindset
Ability to quickly acquire new skills, adapt to unfamiliar technologies, and grow from mistakes. Demonstrate curiosity and commitment to continuous learning.
Practice Interview
Study Questions
Collaboration and Communication
Ability to work effectively in teams, communicate clearly with diverse stakeholders, ask for help when needed, and contribute to team success. Show you value others' input.
Practice Interview
Study Questions
Frequently Asked Frontend Developer Interview Questions
You're hired as a staff frontend engineer to lead cross-team upskilling on web components and design systems. Provide a detailed 90-day plan with goals for discovery, pilot projects, training materials, success metrics, stakeholder engagement, and a roadmap to scale to other teams. Include concrete examples and measurable outcomes where relevant.
Sample Answer
0–30 days — Discover & Align
- Goals: map current frontend stacks, identify component duplication, and secure exec + product + design sponsorship.
- Actions: audit 3 main apps, run 1-hour stakeholder interviews (10 people), catalogue 50+ shared UI patterns.
- Measurable outcomes: audit report, prioritized list of 10 high-impact components, signed charter (sponsor OK).
31–60 days — Pilot & Training
- Goals: prove value with a pilot component library and run initial upskilling.
- Pilot: implement 3 web components (button, modal, data-table) using Lit + TypeScript; publish to npm + Storybook with docs and accessibility tests (axe).
- Training: two 90-minute hands-on workshops + recorded tutorials; create a 1-page cheat sheet and starter repo.
- Measurables: pilot components integrated into 1 product; workshop attendance 30 engineers; baseline accessibility score >= 90; component bundle size < 5 KB gzipped.
61–90 days — Scale & Roadmap
- Goals: onboarding path, governance, and rollout plan.
- Actions: establish contribution guide, semantic versioning policy, CI pipeline (tests, visual diffs), monthly office hours, mentorship pairing across teams.
- Success metrics (quarterly): 30% reduction in duplicated CSS, 20% faster feature delivery for teams adopting components, 50% of teams consuming the library, 90% test coverage on core components.
- Stakeholder engagement: monthly demos to product/design, quarterly roadmap review, and ~4 engineering champions across teams.
Deliverables: audit + pilot repo + Storybook + training materials + governance docs + 90-day KPI dashboard.
What are over-fetching and under-fetching in client-server APIs, and how do REST and GraphQL each deal with them? Describe what a frontend or mobile client feels from each approach.
Sample Answer
Direct answer
Over-fetching means the response carries more data than the screen uses. Under-fetching means one response is not enough, so the client must make follow-up requests to assemble a screen. Both waste the client's time, data allowance and battery. REST fixes them by shaping resources and endpoints on the server: sparse fieldsets (a fields= parameter that lists the only fields the client wants, shown below), embedded related data, or screen-specific endpoints. GraphQL, a query language where the server publishes a schema (a typed list of every object and field a client may ask for), fixes them by letting the client name exactly the fields it wants in a single request, at the price of a heavier server and a harder caching story.
What each problem looks like
Take a feed screen. Each row shows a post title, the author's name and a thumbnail.
- Over-fetching.
GET /postsreturns the whole post: body text, tags, view counts, edit history. The row uses three fields. If each post is 2,000 bytes and a row needs about 100, a page of 20 rows downloads 20 x 2,000 = 40,000 bytes to render 20 x 100 = 2,000 bytes of content, a factor of 20. The phone also parses all of it as JSON (JavaScript Object Notation) and holds it in memory. - Under-fetching.
GET /postsreturnsauthorIdbut not the name. If the 20 posts have 3 distinct authors, the client makes 1 + 3 = 4 requests (the pattern is called N+1: one request for the list, then one more per distinct related item). The author lookups cannot start until the list has arrived, so the screen waits for at least two sequential network round trips (list, then authors), and each extra hop on a weak cellular link is a chance to stall.
How REST deals with it
REST (resources addressed by URL, standard HTTP verbs) has no built-in query language, so you shape responses with conventions:
- Sparse fieldsets:
GET /posts?fields=id,title,author.name,thumbnailUrl. - Embedding or inclusion:
GET /posts?embed=authororinclude=author, so related data rides along (JSON:API, a public REST convention, definesfields[TYPE]andincludeand requires400 Bad Requestwhen a server does not supportinclude). - Screen-shaped endpoints:
GET /screens/feed, which belongs to a Backend-for-Frontend (BFF, a server layer owned by the client team that returns exactly what one client needs).
How GraphQL deals with it
GraphQL exposes one typed schema. The client sends a query that names fields, and the response mirrors its shape:
{ posts(first: 20) { id title author { name } thumbnailUrl(width: 96) } }
Over-fetching disappears because only named fields come back. Under-fetching disappears because the nested author { name } is resolved on the server in the same request (a resolver is the server function that produces the value of one field, here the author's name). Per the GraphQL over HTTP documentation, servers must accept POST for queries and mutations (mutations are the GraphQL operations that write data) and may accept GET for queries only. A response can hold both data and errors, and a response with non-null data should still use a 2xx status, because HTTP has no status for partial success.
What the client feels
| Concern | REST with fieldsets / BFF | GraphQL |
|---|---|---|
| Bytes per screen | Small if the server implements shaping; fixed endpoints over-fetch for other screens | Small by construction, per query |
| Round trips | 1 with embeds or a screen endpoint, otherwise 1 + N (one list request plus one per related item) | 1 per screen query |
| Client CPU | Parses a small JSON; no query building | Parses a small JSON; a client library may normalize results into a cache (split each response into one record per object, keyed by id, so an author shared by many posts is stored once), and that splitting and merging costs CPU on low-end devices |
| CDN (content delivery network) caching | Easy: URL is the cache key, GET is cacheable | Hard with POST; possible with GET plus persisted query ids (short identifiers that replace long query text, which also avoids URL length limits) |
| Developer velocity | Frontend waits for a new field or endpoint if the shape is missing | Frontend adds a field to its own query, no backend ticket, if the schema already exposes it |
| Versioning | New fields are additive; breaking shapes need /v2 or negotiation | Add fields freely and mark old ones with the built-in @deprecated directive (an annotation on a schema field that tells tools and developers the field is going away); usage is visible per field |
| Error handling | HTTP status per request tells the story | Often HTTP 200 with an errors array and partial data, so clients must inspect the body |
Which screens feel it most
- Personalized feed: many small rows, several related entities per row (author, counts, reaction). Under-fetching dominates, so one composed request (GraphQL query or BFF endpoint) matters most.
- Settings screen: one small object, rarely changing. Plain REST is fine and caches well; GraphQL adds little.
- Analytics sync: the client uploads or downloads bulk data in the background. The cost is bytes and radio wake-ups (every time the phone's cellular radio leaves idle to send a request it draws extra battery, so many small requests cost more energy than one batched request), not flexible field choice. Batch it into one request and compress it; a query language is not the lever.
Pitfalls
- GraphQL does not remove over-fetching on the server: a resolver (the function that produces one field) may still load the whole database row. Field selection saves wire bytes, not necessarily database work.
- A permissive
fields=parameter can leak internal columns. Validate it against an allowlist. - Choosing GraphQL to fix under-fetching, then discovering that each nested field issues its own database query (the N+1 problem), swaps a client problem for a server one.
A component fetches data whenever a prop (like an id) changes. Rapid prop updates cause an earlier request to resolve after a later one, overwriting state with stale data. Diagnose the race condition and fix it.
Sample Answer
Direct answer. This is a classic out-of-order async race: fix it by tracking which request is CURRENT and ignoring any response that arrives for a request that's since been superseded, rather than trusting whichever response happens to arrive last.
The bug
async function loadUser(id, setState) {
const data = await fetchUser(id);
setState(data); // no check that `id` is still the one we care about
}
If a user rapidly changes the id prop (e.g., clicking through a list quickly), TWO requests can be in flight at once, and whichever one's network response happens to arrive LAST wins -- even if it was requested FIRST. I reproduced this directly: requesting id=1 (slow, 50ms) then immediately requesting id=2 (fast, 5ms), the final displayed state was id=1's data -- the STALE result overwrote the CORRECT, more recent one, purely because of network timing, not request order.
The fix
function makeLoader() {
let currentId = null;
return async function loadUser(id, setState) {
currentId = id;
const data = await fetchUser(id);
if (id !== currentId) return; // a newer request has superseded this one; drop the stale result
setState(data);
};
}
Same reproduction (request id=1 slow, then id=2 fast): the final state correctly showed id=2's data -- the stale response for id=1 was detected as superseded (currentId had already moved to 2 by the time it resolved) and silently discarded.
Why this happens and how to think about it generally
Async operations don't resolve in the order they were STARTED; they resolve in the order their underlying work actually FINISHES, which depends on network conditions outside your control. Any code that assumes 'the last await to resolve corresponds to the last request I made' is making an assumption that's false under real-world network jitter -- the fix pattern (track an identifier for 'what's current,' check it when the async work resolves, ignore stale results) generalizes to any similar scenario: search-as-you-type, any component whose data-fetching key can change faster than the fetch itself completes.
Trade-offs and pitfalls
- A more robust production fix often uses
AbortControllerto actually CANCEL the stale request (saving the wasted network/server work, not just ignoring its result client-side) -- the 'ignore stale results' pattern shown here is simpler and correct for the CLIENT-SIDE symptom, but doesn't save the wasted request itself. - This same race can hide in less obvious places (two independent effects both eventually calling the same
setState, not just a single re-triggered fetch) -- the general principle (only the CURRENT operation's result should be allowed to update state) applies broadly, not just to this one specific code shape.
A UI designer asks you to remove the browser focus outline for buttons and replace it with a subtle box-shadow to match the brand style. Explain why removing focus indicators is problematic, and provide an accessible CSS approach to customize focus visuals while preserving keyboard visibility and supporting high-contrast/system themes.
Sample Answer
Direct answer. Removing the browser's default focus outline without a replacement is a serious accessibility regression, since it removes the ONLY visual signal a sighted keyboard user has for where they currently are on the page; the correct response to a brand-consistency request is proposing a custom focus style that meets the same visibility and contrast requirements as the default, not simply deleting the indicator.
Executed verification. I scanned both the broken and fixed CSS with axe-core to confirm the structural markup itself remains valid in both cases (the defect here is a VISUAL/interaction one that a static accessibility scanner cannot fully verify computationally, since axe checks for CSS property presence and computed contrast where it can, but genuinely assessing "is this focus style visually discoverable" combines automated contrast checking with manual visual/keyboard verification):
/* broken */
button { outline: none; }
/* fixed */
button:focus-visible {
outline: 2px solid #1D4ED8;
outline-offset: 2px;
}
The #1D4ED8 blue against a white button background computes to well above the 3:1 non-text-contrast minimum required for focus indicators, and also clears the stricter 4.5:1 normal-text threshold (recomputed independently from the WCAG relative-luminance formula: linearize each sRGB channel, weight by 0.2126/0.7152/0.0722, then (L_light+0.05)/(L_dark+0.05); #1D4ED8 against white comes to approximately 6.7:1, concretely: #1D4ED8 decodes to R=29, G=78, B=216; each channel divided by 255 and linearized gives roughly 0.0123, 0.0762, and 0.6867 respectively; weighting those by 0.2126/0.7152/0.0722 gives a luminance of about 0.1067 for the blue against 1.0 for white; and (1.0+0.05)/(0.1067+0.05) works out to approximately 6.70:1).
Why removing focus indicators is problematic. A sighted mouse user rarely notices focus outlines are gone, since they don't rely on them to know where they are; a sighted keyboard-only user (someone with a motor impairment who can't use a mouse precisely, or simply someone who prefers keyboard navigation) loses their only way of knowing which element is currently active, effectively making the page unusable for navigation even though every element is technically still focusable and operable.
Accessible alternative respecting brand style. :focus-visible (rather than plain :focus) ensures the custom style only appears for keyboard/programmatic focus, not on every mouse click, addressing the usual underlying reason someone requests outline removal in the first place (the default outline appearing on every mouse click looking visually noisy), without sacrificing keyboard visibility; the outline color, thickness, and offset can be tuned to match brand aesthetics as long as the resulting contrast and size still meet the numeric requirements.
Supporting high-contrast and system themes. outline is not just easier to implement than box-shadow, it is the only one of the two that Windows High Contrast Mode (the CSS forced-colors: active state) reliably preserves. Under forced-colors, the browser overrides most author-specified colors and effects to protect the user's chosen system palette: box-shadow is one of the properties that gets stripped, while a real outline continues to render, generally remapped to a system color, unless the author explicitly opts out with forced-color-adjust: none. That is a second, independent reason to reject the designer's box-shadow proposal specifically: beyond losing the default keyboard-focus signal for everyone, it would disappear entirely for a user with forced-colors or high-contrast mode enabled, a population this exact kind of "cosmetic" CSS change disproportionately affects.
Trade-offs and pitfalls. "Remove the ugly blue outline" is one of the single most common real accessibility regressions in production codebases, precisely because it's usually requested for a legitimate-sounding visual reason (brand consistency) by someone who doesn't realize :focus-visible already solves the actual annoyance (outline-on-every-click) without requiring the indicator's complete removal.
Define the term 'edge case' (and 'corner case') in the context of software testing. Why does systematically identifying them matter more than testing only the happy path? Give at least eight concrete categories, spanning at least three different domains (a generic input-validation example, a production/reliability example, and a data or ML-pipeline example).
Sample Answer
Direct answer
An edge case (or corner case, when two or more boundary conditions intersect) is an input, state, or condition at the extreme or unusual end of what a system is expected to handle, distinct from the 'happy path' of typical, well-formed usage; systematically identifying them matters because production traffic and adversarial users reliably generate exactly these unusual conditions, while happy-path testing alone only proves the system works when everything goes as expected, which is rarely where real defects live.
Structured elaboration: eight categories, spanning multiple domains
- Empty/null: an empty list, a null field, a zero-length string. Example (general software): a search function called with an empty query string.
- Boundary/max-min: values exactly at, or one step past, a defined limit. Example (backend): a pagination
page_sizeparameter at exactly the server-enforced maximum. - Zero/negative: values a numeric field technically accepts as a type but that may be nonsensical for the domain. Example (SRE/production): a negative value in a counter that should only ever increase, signaling either overflow or a bug in the decrement logic.
- Duplicate: repeated values where uniqueness might be silently assumed. Example (general software): two items with the same ID in a list a system expects to be de-duplicated upstream.
- Malformed/invalid type: input that is the wrong shape or type entirely. Example (backend): a JSON field expected to be an integer arriving as a string or an array.
- Out-of-order/concurrent: events or requests arriving in an unexpected sequence, or overlapping in time. Example (SRE/production): a delivery-confirmation event for a message arriving before the message-sent event, due to network reordering.
- Very large/very small scale: inputs at a magnitude far outside typical testing. Example (data/ML pipeline): a categorical feature with hundreds of millions of unique values (e.g. a raw user ID) fed into a one-hot encoder, which can silently exhaust memory.
- Environment/locale-specific: behavior that only manifests under a specific timezone, locale, or platform. Example (general software): a date-parsing function that behaves correctly in the US locale but misinterprets day/month order elsewhere.
Worked example: why happy-path testing alone misses these
A login form tested only with a valid, well-formed email and a correct password will pass every happy-path test while shipping with a null-pointer crash on an empty password field, an infinite spinner on a 10,000-character email, or a silent security bypass on a SQL-injection-shaped username, none of which a happy-path suite would ever exercise, because by construction happy-path tests only feed the system inputs the developer already expected to work.
Trade-offs & pitfalls
Treating 'edge case' as synonymous with 'rare' is a common misconception: an empty list or a zero value is often one of the MOST common real-world inputs (a brand-new user's empty cart, a freshly-created account with no activity yet), not a rare corner case, which is exactly why the empty/null category above is listed first, not last; conflating 'edge case' with 'unlikely' leads teams to systematically under-test the cases that actually occur most often in a real user base's earliest interactions with a feature.
Your browser never sees JSX. Describe what happens to it between source and runtime, which tools take part, and what changed with the automatic runtime.
Sample Answer
Direct answer
JSX (the HTML-like syntax inside JavaScript files) is not valid JavaScript, so a build tool rewrites it before the browser ever sees it. A compiler parses the file into a syntax tree, replaces each JSX element with an ordinary function call that describes the element, and emits plain JavaScript that gets bundled with the rest of the app. The classic transform emits React.createElement(...) calls and needs React in scope. The automatic runtime (React 17 and later) emits calls to jsx and jsxs functions that the compiler imports from react/jsx-runtime itself, so files no longer need import React from 'react'.
What happens, in order
- Source file. A
.jsxor.tsxfile is read by the build tool (a bundler, which is a tool that followsimportstatements and merges many source files into a few files for the browser, such as Vite or webpack, or a framework such as Next.js, calls a compiler for each file). - Parse. The compiler turns the text into an abstract syntax tree (AST, a nested data structure for the program). It understands JSX nodes: elements, attributes,
{expression}holes and text. - Transform. A JSX transform plugin rewrites each element node into a function call. For TypeScript files the type annotations are removed in the same pass (or by a separate step), so the output is JavaScript.
- Lower, bundle, minify. Other transforms run: lowering (rewriting newer syntax into older syntax that older browsers understand), import resolution (bundling), and minification (shrinking the code by shortening names and removing whitespace), and the result is shipped as ordinary JavaScript.
- Runtime. In the browser, the generated calls run and return element objects: plain JavaScript objects with a type, props and key. React reads that tree of objects to decide what to draw on the page. No JSX parsing exists at runtime.
Tools that take part: Babel with @babel/preset-react, and TypeScript's own compiler through its jsx setting (react-jsx selects the automatic runtime), together with whichever bundler or framework invokes them. The React team's announcement names Babel 7.9.0 and above and TypeScript 4.1 and above as supporting the new transform, with Create React App 4.0.0 and Next.js 9.5.3 as examples of toolchains that enable it.
The same component through both transforms
// app.jsx
function Greeting({ name, items }) {
return (
<section className="card" key="g">
<h1>Hello, {name}</h1>
<ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>
</section>
);
}
// compile.mjs
import { readFileSync } from "node:fs";
import { transformSync } from "@babel/core";
const code = readFileSync("app.jsx", "utf8");
for (const runtime of ["classic", "automatic"]) {
const out = transformSync(code, {
babelrc: false, configFile: false,
presets: [["@babel/preset-react", { runtime }]],
}).code;
console.log(`--- @babel/preset-react runtime: ${runtime}\n${out}\n`);
}
Run with Babel 7.29.7, this prints:
--- @babel/preset-react runtime: classic
function Greeting({
name,
items
}) {
return /*#__PURE__*/React.createElement("section", {
className: "card",
key: "g"
}, /*#__PURE__*/React.createElement("h1", null, "Hello, ", name), /*#__PURE__*/React.createElement("ul", null, items.map(i => /*#__PURE__*/React.createElement("li", {
key: i
}, i))));
}
--- @babel/preset-react runtime: automatic
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
function Greeting({
name,
items
}) {
return /*#__PURE__*/_jsxs("section", {
className: "card",
children: [/*#__PURE__*/_jsxs("h1", {
children: ["Hello, ", name]
}), /*#__PURE__*/_jsx("ul", {
children: items.map(i => /*#__PURE__*/_jsx("li", {
children: i
}, i))
})]
}, "g");
}
The /*#__PURE__*/ comments in both outputs are annotations the compiler adds. They tell the minifier and bundler that the call has no side effects, so a call whose result is never used can be deleted (tree shaking, dropping code that nothing uses). Babel's preset-react controls this with its pure option, on by default, which the Babel docs describe as marking React calls as pure for tree shaking. They do not change what the code does when it runs.
What changed with the automatic runtime
| Aspect | Classic | Automatic |
|---|---|---|
| Call emitted | React.createElement(type, props, ...children) | jsx(type, props, key) for one child, jsxs for several children |
React import needed in every JSX file | Yes: the output refers to a variable named React | No: the compiler adds import { jsx } from "react/jsx-runtime" |
| Children | Extra arguments after props | Inside props as children |
key | A normal prop inside the props object | Passed as a separate third argument (see "g" and i above) |
In development builds the compiler uses react/jsx-dev-runtime, and the React team notes that these runtime modules are meant to be called only by the compiler, never by hand. Upgrading is optional; the classic transform still works.
Pitfalls
React is not defined. Code compiled with the classic transform fails at runtime ifReactis not imported. The fix is to switch the compiler to the automatic runtime (Babel'sruntime: "automatic", TypeScript'sjsx: "react-jsx") or add the import.- Hooks still need imports. The automatic runtime removes only the import needed for JSX itself;
useStateand other exports still have to be imported fromreact. - Mismatched settings. A bundler configured for automatic while TypeScript or Babel is still on classic yields mixed output and the
React is not definederror above. Check the one place JSX is compiled. - JSX is not a template string. Every
{...}hole is a JavaScript expression evaluated when the function runs, which is whyitems.map(...)inside JSX produces an array of elements.
Running the code
# Node 22, with app.jsx and compile.mjs saved in an empty folder
npm i @babel/core@7 @babel/preset-react@7
node compile.mjs
Toggling a CSS custom property at runtime causes a lot of repaints and visible jank in a large app. Why can changing a variable be expensive, and how do you limit the scope of the work it triggers?
Sample Answer
Short answer: a CSS custom property (a variable declared as --name: value and read with var(--name)) is inherited by default (passed from an element down to everything nested inside it unless a descendant overrides it), so writing it on an ancestor means every descendant might now compute a different value. The browser recalculates style across the subtree (the element and everything nested inside it), restyling every descendant whose style uses any variable, which, as the demo shows, includes elements that never mention the changed one; and if the variable feeds a layout property such as padding it also redoes layout. You limit the work by writing the variable on the smallest element that needs it, never driving per-frame values through :root, and shrinking the DOM the write can reach.
The mechanism
When a declaration changes, the browser runs style recalculation: for each affected element it re-resolves which rules apply and computes the final values. For a normal property such as color on one element, that is one element. A custom property is different because inheritance is its default behaviour: the new value flows down to every descendant, and any descendant's var() could depend on it. So the set of elements to recalculate is every descendant under the element you wrote to whose style uses a variable, whichever variable it names. In the Chromium trace below, the 100 section wrappers, whose rules use no var(), were not counted; using a variable is a good predictor of what gets restyled, not a complete rule (a few page-level elements that use none are restyled too). Then, depending on which real properties read the variable, the browser repeats layout (geometry, for properties like padding and width) and paint (pixels, for color and background).
Measured on a 15,106-element page
The demo has 5,000 cards, each with a title and a badge (three elements per card), in 100 sections of 50 cards, all reading --accent, and a separate #cursor widget. It counts how many elements the browser restyled, using a Chromium trace. recalcEvents is the number of style recalculation passes (Chromium's Recalculate Style), elementsRecalculated is the total elements those passes restyled, and layouts is the number of layout passes:
trace.mjs
// Shared helper: run `action` while Chromium traces, return per-event counts.
export async function traced(browser, page, action) {
await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] });
await action();
const trace = JSON.parse((await browser.stopTracing()).toString());
const ev = trace.traceEvents.filter((e) => e.ph === 'X');
const n = (name) => ev.filter((e) => e.name === name);
return {
layout: n('Layout').length,
recalc: n('UpdateLayoutTree').length,
recalcElements: n('UpdateLayoutTree').reduce((s, e) => s + (e.args?.elementCount ?? 0), 0),
paint: n('Paint').length,
layoutObjects: n('Layout').reduce((s, e) => s + (e.args?.beginData?.dirtyObjects ?? 0), 0),
};
}
custom-props.mjs
import { chromium } from 'playwright';
import { traced } from './trace.mjs';
const BREAK = process.env.BREAK === '1'; // fault injection: the "scoped" writes target :root again
const SECTIONS = 100, PER = 50; // 5,000 cards, each with a title and a badge
const css = `
:root{--accent:#36c;--gap:4px;--x:0}
.card{color:var(--accent);padding:var(--gap)}
.card .title{border-left:2px solid var(--accent)}
.card .badge{background:var(--accent)}
#cursor{transform:translateX(calc(var(--x) * 1px))} #cursor i{color:var(--accent)}`;
const html = `<!doctype html><style>${css}</style><div id=cursor><i>dot</i></div>` + Array.from({ length: SECTIONS }, (_, s) =>
`<section class=section id=s${s}>${Array.from({ length: PER }, () => '<div class=card><span class=title>t</span><i class=badge>b</i></div>').join('')}</section>`).join('');
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
const total = await page.evaluate(() => document.getElementsByTagName('*').length);
const parts = await page.evaluate(() => ({ cardElements: document.querySelectorAll('.card, .card *').length, sections: document.getElementsByTagName('section').length }));
const settle = () => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
const run = async (fn, arg) => { await settle(); return traced(browser, page, async () => { await page.evaluate(fn, arg); await settle(); }); };
const rows = {};
rows['--accent on :root, read by 3 elements per card'] = await run(() => document.documentElement.style.setProperty('--accent', '#c33'));
rows['--accent on one section'] = await run((b) => (b ? document.documentElement : document.getElementById('s7')).style.setProperty('--accent', '#3c3'), BREAK);
rows['--gap on :root, read by padding'] = await run(() => document.documentElement.style.setProperty('--gap', '6px'));
const perFrame = (target) => run(([t, frames]) => new Promise((resolve) => {
const el = t === 'root' ? document.documentElement : document.getElementById('cursor'); let i = 0;
(function step() { el.style.setProperty('--x', i * 4); if (++i < frames) requestAnimationFrame(step); else resolve(); })();
}), [target, 30]);
rows['30 per-frame writes of --x on :root'] = await perFrame('root');
rows['30 per-frame writes of --x on #cursor'] = await perFrame(BREAK ? 'root' : 'cursor');
await browser.close();
console.log(`elements in page: ${total} = ${parts.cardElements} in cards + ${parts.sections} sections + ${total - parts.cardElements - parts.sections} others (html, head, style, body, #cursor and its child)`);
console.table(Object.fromEntries(Object.entries(rows).map(([k, v]) => [k, { recalcEvents: v.recalc, elementsRecalculated: v.recalcElements, layouts: v.layout }])));
const [root, one, gap, frameRoot, frameCursor] = Object.values(rows);
const inner = SECTIONS * PER * 3, fail = [];
if (root.recalcElements < inner * 0.95) fail.push(`root write recalculated ${root.recalcElements}, expected about ${inner}`);
if (one.recalcElements > PER * 3 + 5) fail.push(`scoped write recalculated ${one.recalcElements}, expected about ${PER * 3}`);
if (gap.layout < 1) fail.push('a variable read by padding should force layout');
if (frameRoot.recalcElements < inner * 0.95 * 25) fail.push(`per-frame root writes recalculated only ${frameRoot.recalcElements}`);
if (frameCursor.recalcElements > 30 * 10) fail.push(`per-frame cursor writes recalculated ${frameCursor.recalcElements}`);
if (fail.length) { console.error('FAIL\n' + fail.join('\n')); process.exit(1); }
console.log('PASS');
Run in a mcr.microsoft.com/playwright:v1.48.2-jammy container (Chromium 130.0.6723.31, headless, Linux), it prints:
elements in page: 15106 = 15000 in cards + 100 sections + 6 others (html, head, style, body, #cursor and its child)
┌────────────────────────────────────────────────┬──────────────┬──────────────────────┬─────────┐
│ (index) │ recalcEvents │ elementsRecalculated │ layouts │
├────────────────────────────────────────────────┼──────────────┼──────────────────────┼─────────┤
│ --accent on :root, read by 3 elements per card │ 1 │ 15005 │ 0 │
│ --accent on one section │ 1 │ 151 │ 0 │
│ --gap on :root, read by padding │ 1 │ 15006 │ 1 │
│ 30 per-frame writes of --x on :root │ 29 │ 435174 │ 0 │
│ 30 per-frame writes of --x on #cursor │ 29 │ 58 │ 0 │
└────────────────────────────────────────────────┴──────────────┴──────────────────────┴─────────┘
PASS
exit=0
Reading the table:
- The page has 15,106 elements: 5,000 cards x 3 elements (the card, its title and its badge) = 15,000, plus 100 section wrappers, plus 6 others. Writing
--accenton:rootrestyled 15,005 of them in one recalculation: all 15,000 card elements and 5 of the 6 others. The 100 section elements are not in the count: no rule gives them a value that uses a variable, and Chromium skipped them. Using a variable predicts what is restyled here but is not a complete rule, since the 5 restyled "others" include page-level elements that use none. Writing the same variable on one section restyled 151: the section plus its 50 cards x 3 elements = 1 + 150. - The
--gapvariable, read bypadding, also triggered a layout event; a variable that feeds a layout property turns a style cost into a layout cost. - The per-frame case is where jank appears. Only
#cursorreads--x, yet writing--xon:rootfor 30 frames produced 29 style recalculations of 15,006 elements each: 29 x 15,006 = 435,174 element restyles in half a second. That is the evidence that the cost follows the variable-using elements under the write, not the number of elements that read the variable being written. Writing the same value on#cursorrestyled 58 elements in total (2 per recalculation, the widget and its child). Frame budgets are 16.67 ms at 60 Hz, so restyling 15,000 elements every frame is the pattern to look for when a phone drops frames. The counts are element totals, not milliseconds.
How to limit the scope
- Write where it is read. Set the variable on the component's root element, not on
:rootorbody. The browser then only restyles that subtree. - Keep high-frequency values off the root. Pointer position, scroll progress and drag offsets change every frame. Put them on the small element that uses them, or write the real property directly (
el.style.transform = ...). - Reserve root-level variables for rarely-changing tokens such as a theme switch. That costs one recalculation per switch, which a user will not notice, instead of one per frame.
- Do not let a variable feed layout properties if it changes often.
- Make the subtree smaller. The cost is proportional to the number of variable-using elements the write can reach, so virtualizing long lists (render only the rows near the viewport) also shrinks every variable write.
How to confirm it in a real app
Record a performance trace of the interaction and look for long Recalculate Style events on the main thread (Chrome's DevTools docs use that name, and offer an option to "view the statistics of your CSS rule selectors during long-running Recalculate Style events"). A single recalculation covering most of the page after a one-line variable change is the signature. Then write the variable on the narrower element and record again; the demo's BREAK=1 mode, which writes the "scoped" variables on :root again, shows the same signature and fails the script. It prints:
elements in page: 15106 = 15000 in cards + 100 sections + 6 others (html, head, style, body, #cursor and its child)
┌────────────────────────────────────────────────┬──────────────┬──────────────────────┬─────────┐
│ (index) │ recalcEvents │ elementsRecalculated │ layouts │
├────────────────────────────────────────────────┼──────────────┼──────────────────────┼─────────┤
│ --accent on :root, read by 3 elements per card │ 1 │ 15005 │ 0 │
│ --accent on one section │ 1 │ 15005 │ 0 │
│ --gap on :root, read by padding │ 1 │ 15005 │ 1 │
│ 30 per-frame writes of --x on :root │ 29 │ 435145 │ 0 │
│ 30 per-frame writes of --x on #cursor │ 29 │ 435145 │ 0 │
└────────────────────────────────────────────────┴──────────────┴──────────────────────┴─────────┘
FAIL
scoped write recalculated 15005, expected about 150
per-frame cursor writes recalculated 435145
exit=1
An @property rule registers a custom property with a declared type; it must give both a syntax and an inherits descriptor, and inherits: false registers the property as not inherited by default (MDN: the descriptor "controls whether the custom property registration specified by @property inherits by default"). Whether that reduces the restyle count in your app is a measurement to take with the same trace, not an assumption.
Trade-offs and pitfalls
- Scoping the variable means components that need the same value must each receive it, which costs some theme-token convenience. A common compromise is token variables on
:root(rarely changed) and animated variables on the component. - Moving a per-frame value off a custom property usually means writing
transformoropacitydirectly, which is cheaper anyway. - The counts come from a Chromium trace; other engines may decide differently which descendants to restyle, so repeat the trace in each browser you target.
- A recalculation count says how much work, not how long it took. Confirm with the frame-rate overlay or a trace on the target device.
Running the code
mkdir props && cd props
printf '{"type":"module","dependencies":{"playwright":"1.48.2"}}' > package.json
# save trace.mjs and custom-props.mjs here, then (the second run uses BREAK=1):
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \
'npm i --silent; node custom-props.mjs; echo exit=$?; BREAK=1 node custom-props.mjs; echo exit=$?'
Tell me about a time you received critical feedback about your communication, collaboration, or leadership style, rather than about a specific piece of work. How did you process it, what's one concrete change you made, and what was the measurable result?
Sample Answer
Direct answer
Separate the trait from your identity, "I do this," not "I am this kind of person," turn the feedback into one specific, observable behavior to change rather than a vague personality fix, and track the result through what other people start doing differently, not a self-reported feeling.
Structured elaboration
- Processing the feedback. Interpersonal-style feedback lands harder than technical feedback because it can feel like a judgment of character rather than of output. The reframe that helps is translating it into a specific behavior, "I interrupt people mid-thought in meetings," not "I'm not a good listener," since behaviors are changeable and traits feel fixed and personal.
- Choosing the concrete change. Pick one observable habit to change, not a general resolution. A rule you can self-check in the moment, "let people finish their sentence before I respond, count one beat of silence first," beats a vague intention to "communicate better."
- Assessing the result honestly. Interpersonal change is genuinely hard to quantify, so the honest signal is behavioral and relational, not a number: being looped into a discussion earlier than before, a colleague raising a half-formed idea with you again without hesitation, the original feedback-giver mentioning unprompted that they noticed a difference.
Worked example
A skip-level review noted that I tended to jump in with a solution before people finished describing the problem, which read as dismissive even though I didn't mean it that way. I turned that into one concrete habit: in any discussion, let the other person finish their point fully, then pause a beat before responding, even if I already thought I knew the answer. The result wasn't a score, it was that a teammate who'd previously stopped bringing half-formed ideas to me started doing it again, and my manager mentioned in a later one-on-one, unprompted, that meetings with me felt less rushed.
Trade-offs and pitfalls
Reporting a precise, fabricated metric, like "my collaboration score went from 3 to 4.5," for something this qualitative is a red flag to an interviewer, not a strength; interpersonal change is real but rarely cleanly measurable, and claiming false precision undercuts credibility rather than adding to it. Treating the feedback as globally true about your whole personality, rather than true in specific contexts, tends to produce overcorrection, going silent in meetings instead of just pausing. And a change nobody else notices isn't actually demonstrated; the answer needs an external signal, even a small one, not just your own resolve.
Build a small global store in React for a shopping cart (add, remove, clear) that any component can read and update, so that a component showing only the item count does not re-render when an unrelated field changes. Show the code.
Sample Answer
Direct answer
Keep the cart in a small store that lives outside React's render cycle (a plain object with getState, dispatch and subscribe: dispatch sends it an action, a plain object such as { type: 'add', id: 'p1' } describing what happened, and a reducer, a function (state, action) => nextState, computes the new state), put only the store object in context, and let each component subscribe to just the slice it needs (a slice is one part of the state, such as the item count or the banner text) with useSyncExternalStore. A component that returns selectCount(state) is re-rendered only when that number changes, so editing an unrelated field such as a banner message never touches it. If you instead put the whole state object in a context value, every consumer re-renders on every change, which the last test below demonstrates.
How it works
- The store holds
state, applies a reducer ondispatch, and calls its listeners only when the reducer returned a different object. A no-op action (clearing an already empty cart) therefore notifies nobody. - The context holds the store itself. The store object never changes identity, so the provider never forces anything to re-render. Context here is a way to find the store without prop drilling (passing it down through every component), not the channel that carries updates.
useSyncExternalStore(subscribe, getSnapshot)is React's hook for reading an external store. react.dev says: "Thesubscribefunction should subscribe to the store and return a function that unsubscribes." and "While the store has not changed, repeated calls togetSnapshotmust return the same value." (https://react.dev/reference/react/useSyncExternalStore). OurgetSnapshotisselector(store.getState()). React compares each result with the previous one usingObject.isand re-renders only if it differs. A selector that returns a number or string is stable between unrelated changes.
What the reducer does to a small state, step by step. The test dispatches setBanner with 'Sale' first, so every row below carries that banner:
| Action | State before | State after | Listeners notified? |
|---|---|---|---|
add p1 | { items: [], banner: 'Sale' } | { items: [{ id: 'p1', name: 'Pen', qty: 1 }], banner: 'Sale' } | yes (new object) |
add p1 again | the state above | the p1 line becomes qty: 2 (map copies the list and the changed line) | yes |
add p2 | p1 with qty: 2 | p1 (qty: 2) plus { id: 'p2', name: 'Ink', qty: 1 }, so selectCount is 3 | yes |
remove p1 | both lines | only p2, so selectCount is 1 | yes |
remove nope | only p2 | the same object is returned (some found nothing) | no |
clear | only p2 | { items: [], banner: 'Sale' } (new object, qty total 0) | yes |
clear again | empty cart | the same object is returned | no |
The identity check that decides "notified?" is Object.is(next, state) in dispatch: when the reducer hands back the very same object, the two are identical and the store returns early; any new object, even with equal contents, counts as a change.
The code
// cartStore.jsx
import { createContext, useContext, useSyncExternalStore } from 'react';
export const initialCart = { items: [], banner: '' };
export function cartReducer(state, action) {
switch (action.type) {
case 'add': {
const found = state.items.find((i) => i.id === action.id);
const items = found
? state.items.map((i) => (i.id === action.id ? { ...i, qty: i.qty + 1 } : i))
: [...state.items, { id: action.id, name: action.name, qty: 1 }];
return { ...state, items };
}
case 'remove':
return state.items.some((i) => i.id === action.id)
? { ...state, items: state.items.filter((i) => i.id !== action.id) }
: state;
case 'clear':
return state.items.length === 0 ? state : { ...state, items: [] };
case 'setBanner':
return state.banner === action.text ? state : { ...state, banner: action.text };
default:
return state;
}
}
export function createStore(reducer, initialState) {
let state = initialState;
const listeners = new Set();
return {
getState: () => state,
dispatch(action) {
const next = reducer(state, action);
if (Object.is(next, state)) return; // nothing changed: nobody is notified
state = next;
listeners.forEach((l) => l());
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
}
const StoreContext = createContext(null);
export function CartProvider({ store, children }) {
// The context value is the store object itself. It never changes, so the
// provider never forces consumers to re-render.
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
}
export function useCartSelector(selector) {
const store = useContext(StoreContext);
return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}
export function useCartDispatch() {
return useContext(StoreContext).dispatch;
}
export const selectCount = (s) => s.items.reduce((n, i) => n + i.qty, 0);
export const selectBanner = (s) => s.banner;
Tests with render counts
The test counts how many times each component function runs. It checks the cart count through add (new line, existing line), remove (present and absent id) and clear (non-empty and already empty), proves the count component stays out of banner updates, and then renders the same count component against a whole-state context value as the baseline that must fail the "stays at 1" claim. One test subscribes a plain listener to the store and checks that no-op actions (unknown id, empty clear, unchanged banner, unknown action type) never call it, because render counts alone cannot show that: the selected number is the same either way. A last test uses a selector that builds a new object on every call.
// cartStore.test.jsx
import { describe, it, expect, vi, afterEach } from 'vitest';
import { createContext, useContext, useReducer, useRef } from 'react';
import { render, screen, act, cleanup } from '@testing-library/react';
afterEach(cleanup);
import {
CartProvider, createStore, cartReducer, initialCart,
useCartSelector, useCartDispatch, selectCount, selectBanner,
} from './cartStore.jsx';
const renders = { count: 0, banner: 0 };
function CartCount() {
renders.count += 1;
const n = useCartSelector(selectCount);
return <span data-testid="count">{n}</span>;
}
function Banner() {
renders.banner += 1;
const t = useCartSelector(selectBanner);
return <span data-testid="banner">{t}</span>;
}
function setup() {
renders.count = 0; renders.banner = 0;
const store = createStore(cartReducer, initialCart);
render(<CartProvider store={store}><CartCount /><Banner /></CartProvider>);
return store;
}
describe('store with selector subscriptions', () => {
it('count component ignores unrelated fields and tracks add/remove/clear', () => {
const store = setup();
expect([renders.count, renders.banner]).toEqual([1, 1]);
act(() => store.dispatch({ type: 'setBanner', text: 'Sale' }));
expect(screen.getByTestId('banner').textContent).toBe('Sale');
expect([renders.count, renders.banner]).toEqual([1, 2]);
act(() => store.dispatch({ type: 'add', id: 'p1', name: 'Pen' }));
act(() => store.dispatch({ type: 'add', id: 'p1', name: 'Pen' }));
act(() => store.dispatch({ type: 'add', id: 'p2', name: 'Ink' }));
expect(screen.getByTestId('count').textContent).toBe('3');
expect(renders.count).toBe(4);
act(() => store.dispatch({ type: 'remove', id: 'p1' }));
expect(screen.getByTestId('count').textContent).toBe('1');
act(() => store.dispatch({ type: 'remove', id: 'nope' })); // no-op
act(() => store.dispatch({ type: 'clear' }));
expect(screen.getByTestId('count').textContent).toBe('0');
const afterClear = renders.count;
act(() => store.dispatch({ type: 'clear' })); // already empty: no-op
expect(renders.count).toBe(afterClear);
console.log('selector store: CartCount renders =', renders.count, '| Banner renders =', renders.banner);
});
it('no-op actions notify nobody, and a real change notifies once', () => {
const store = createStore(cartReducer, initialCart);
const listener = vi.fn();
store.subscribe(listener);
store.dispatch({ type: 'remove', id: 'nope' });
store.dispatch({ type: 'clear' });
store.dispatch({ type: 'setBanner', text: '' });
store.dispatch({ type: 'unknown' });
expect(listener).not.toHaveBeenCalled();
store.dispatch({ type: 'add', id: 'p1', name: 'Pen' });
expect(listener).toHaveBeenCalledTimes(1);
});
it('a component can update through the dispatch hook', () => {
const store = createStore(cartReducer, initialCart);
function AddButton() {
const dispatch = useCartDispatch();
return <button onClick={() => dispatch({ type: 'add', id: 'p1', name: 'Pen' })}>add</button>;
}
render(<CartProvider store={store}><AddButton /><CartCount /></CartProvider>);
act(() => screen.getByText('add').click());
expect(screen.getByTestId('count').textContent).toBe('1');
});
it('pitfall: a selector that builds a new object on every call is reported by React', () => {
const store = createStore(cartReducer, initialCart);
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
function Bad() {
const v = useCartSelector((s) => ({ n: s.items.length }));
return <span>{v.n}</span>;
}
let thrown = null;
try { render(<CartProvider store={store}><Bad /></CartProvider>); } catch (e) { thrown = e; }
const msgs = spy.mock.calls.map((c) => String(c[0]) + ' ' + String(c[1] ?? '')).join('\n');
spy.mockRestore();
console.log('thrown:', thrown && thrown.message.slice(0, 60));
console.log('first matching console.error line:', msgs.split('\n').find((l) => /getSnapshot/.test(l)));
console.log('console.error mentions getSnapshot caching:', /getSnapshot should be cached/.test(msgs));
expect(thrown !== null || /getSnapshot should be cached/.test(msgs)).toBe(true);
});
});
describe('without selectors (whole state in one context value)', () => {
it('the count component re-renders when the banner changes', () => {
const Ctx = createContext(null);
const c = { count: 0 };
let dispatchOut;
function Count() { c.count += 1; const { state } = useContext(Ctx); return <span>{selectCount(state)}</span>; }
function Root() {
const [state, dispatch] = useReducer(cartReducer, initialCart);
dispatchOut = dispatch;
return <Ctx.Provider value={{ state, dispatch }}><Count /></Ctx.Provider>;
}
render(<Root />);
act(() => dispatchOut({ type: 'setBanner', text: 'Sale' }));
console.log('whole-state context: CartCount renders =', c.count);
expect(c.count).toBe(2); // fails the selector store's "stays at 1" claim
});
});
Run with the setup below, the whole runner output (the Start at and Duration timing lines are removed with grep -vE 'Start at|Duration|^$') is:
RUN v2.1.8 /w
stdout | cartStore.test.jsx > store with selector subscriptions > count component ignores unrelated fields and tracks add/remove/clear
selector store: CartCount renders = 6 | Banner renders = 2
stdout | cartStore.test.jsx > store with selector subscriptions > pitfall: a selector that builds a new object on every call is reported by React
thrown: Maximum update depth exceeded. This can happen when a compon
first matching console.error line: Warning: The result of getSnapshot should be cached to avoid an infinite loop%s
console.error mentions getSnapshot caching: true
stdout | cartStore.test.jsx > without selectors (whole state in one context value) > the count component re-renders when the banner changes
whole-state context: CartCount renders = 2
✓ cartStore.test.jsx > store with selector subscriptions > count component ignores unrelated fields and tracks add/remove/clear
✓ cartStore.test.jsx > store with selector subscriptions > no-op actions notify nobody, and a real change notifies once
✓ cartStore.test.jsx > store with selector subscriptions > a component can update through the dispatch hook
✓ cartStore.test.jsx > store with selector subscriptions > pitfall: a selector that builds a new object on every call is reported by React
✓ cartStore.test.jsx > without selectors (whole state in one context value) > the count component re-renders when the banner changes
Test Files 1 passed (1)
Tests 5 passed (5)
Each stdout | header names the test that printed the lines under it. In the pitfall test, thrown: is the first 60 characters of the error React threw out of render, and first matching console.error line: is the first line React logged that mentions getSnapshot; both come from the Bad component, whose selector returns a new { n: ... } object on every call.
Reading it: CartCount rendered once on mount, did not re-render for the banner change, then rendered five more times for the five actions that changed the number (add, add, add, remove, clear). That is 6 in total. The banner component rendered twice (mount plus one banner change). With the whole-state context value the same component rendered twice after a single banner change.
Trade-offs and pitfalls
- Selectors must return stable values. Returning
{ n: ... }or.filter(...)from a selector creates a new object on each call, so React sees a changing snapshot on every check. In the run above React logged the warning shown and threw "Maximum update depth exceeded". Select primitives, select an existing object that the reducer preserved, or compute derived arrays outside the selector. - Never mutate state in the reducer. Listeners are only notified when the reducer returns a new object, and
Object.isequality is what React uses to decide a re-render. - Server rendering needs a third argument. Server rendering means React turns the component tree into an HTML string on a server (for example with
renderToString) before the browser takes over. react.dev says that if you omitgetServerSnapshot, "rendering the component on the server will throw an error." With the store above,renderToStringon a tree containing auseCartSelectorcomponent throwsMissing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.in React 18.3.1. If this store is used in server-rendered pages, pass a third function that returns the snapshot the server should render, such as() => selector(initialCart). - Ready-made options. Redux Toolkit ("our official recommended approach for writing Redux logic", https://redux.js.org/introduction/getting-started) is the established library for this shape. Recommendation: hand-rolling is reasonable for a cart; adopt a library when you need middleware (code that sits between
dispatchand the reducer to log, delay or transform actions), devtools (a browser extension that records every action and state for debugging) or many slices. - Complexity.
dispatchruns the reducer once and then every listener's selector, so the cost per dispatch is the number of listeners multiplied by the cost of one selector (written O(listeners x selector cost); O(...) describes how work grows with size).selectCountis O(lines). With thousands of subscribers, give each its own narrow selector or key listeners by slice. - Edge cases covered by the tests: adding the same product twice increments quantity, removing an unknown id and clearing an empty cart do nothing, and unrelated field changes do not re-render the count.
Running the code
Files: cartStore.jsx, cartStore.test.jsx, vitest.config.js.
npm init -y && npm pkg set type=module
npm i react@18.3.1 react-dom@18.3.1
npm i -D vitest@2.1.8 jsdom@25.0.1 @testing-library/react@16.1.0 @testing-library/dom@10.4.0
# vitest.config.js: export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } }
npx vitest run --reporter=verbose 2>&1 | grep -vE 'Start at|Duration|^$'
Run in a node:22 container (Node 22.23.3) with exactly those versions.
Design a data structure that supports insert(value), remove(value), and getRandom() so that every currently-stored value is equally likely to be returned, with all three operations running in expected O(1) time. A hash set alone gives you O(1) insert/remove but not uniform O(1) random access; explain what you add to fix that.
Sample Answer
Direct answer
Keep a resizable array of the stored values plus a hash map from value to that value's index in the array. Insert appends to the array in O(1); getRandom picks a uniformly random array index in O(1); the trick is delete, which must not leave a gap: swap the removed value with the array's last element, update that moved element's index in the hash map, then pop the last slot off in O(1).
Structured elaboration
values: an array of the currently stored values, with no gaps.index_of: hash map from value to its current position invalues.
insert(val): if val is already in index_of, return false. Otherwise append it to values and record its index.
remove(val): if val is absent, return false. Otherwise look up its index, overwrite that slot with the array's last element (updating that moved element's entry in index_of to the vacated index), then pop the array's last slot and delete val from index_of. Because the moved element simply changes which index it lives at, and every array slot is always occupied by exactly one live value, no gap is ever created and no shifting of the remaining elements is needed.
getRandom(): choose a uniformly random integer index in [0, len(values)) and return values[that index]. Since each stored value occupies exactly one slot and slots are chosen uniformly, every value has equal probability of being returned.
The reason a plain hash set cannot support getRandom in O(1) is that hash tables give you no way to address "the k-th element" directly: you would need to walk buckets, which is not O(1) and not uniform once buckets have different chain lengths. The array gives you that direct O(1) addressing that a hash table structurally lacks.
Worked example
import random
class RandomizedSet:
def __init__(self):
self.index_of: dict[int, int] = {}
self.values: list[int] = []
def insert(self, val: int) -> bool:
if val in self.index_of:
return False
self.index_of[val] = len(self.values)
self.values.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.index_of:
return False
idx = self.index_of[val]
last_val = self.values[-1]
self.values[idx] = last_val
self.index_of[last_val] = idx
self.values.pop()
del self.index_of[val]
return True
def get_random(self) -> int:
return random.choice(self.values)
random.seed(42)
rs = RandomizedSet()
print(rs.insert(1))
print(rs.insert(2))
print(rs.insert(3))
print(rs.remove(2)) # swaps 3 into index 1
print(rs.values)
print(rs.get_random())
print(rs.get_random())
Running this (CPython's random module, seeded) prints:
True
True
True
True
[1, 3]
1
1
Key points
- The swap-with-last trick is what keeps delete O(1): it avoids shifting every element after the removed one.
- Uniformity comes from the array having no gaps:
random.choiceover indices is exactly a uniform choice over the stored values.
Complexity
O(1) averagefor insert, remove, and getRandom; O(n) space for the array and hash map together.
Edge cases
- Removing the last element in the array: the "swap with last" step is swapping an element with itself, which is harmless.
getRandomon an empty structure has no valid answer; guard it explicitly (raise, or document as undefined behavior) rather than lettingrandom.choicethrow an unhandled exception on an empty list.
Trade-offs & pitfalls
The most common mistake is deleting by shifting all elements after the removed index, which is correct but O(n), defeating the point. A second common mistake is deleting by using values.remove(val) in Python, which internally does that same O(n) scan-and-shift. The design absorbs a lighter-weight sibling problem well: an insertion-order-preserving set (for example, deduplicating items in a shopping cart while keeping display order) uses the same "array plus hash map of positions" composition, but it cannot use the swap-with-last trick, because swapping would destroy the insertion order it is trying to preserve. That variant instead needs either a tombstone marker left in place (with periodic compaction) or a doubly linked list plus hash map (the same structure used for an LRU cache), trading away the O(1) swap-delete for order preservation.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Frontend Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs