Machine Coding · Lesson 11 of 12 · 5 min
Performance Optimization Techniques
This is how you answer "how would you make this faster?" with specifics, not just hand-waving.
After this lesson, you'll be able to identify performance bottlenecks and apply the right fix. You won't just say "memoization"; you'll explain why a component re-renders and how React.memo or useMemo solves that specific problem. You'll know when to debounce, when to virtualize, and when to use a Web Worker.
First, prove it's slow
Don't guess. The first step in any performance task is to measure. Premature optimization is a waste of time and adds complexity for no reason.
Use the Performance tab in your browser's developer tools. Record a user interaction you believe is slow, like typing in a search box or scrolling a long list. Look for long tasks (yellow bars with red triangles) on the main thread timeline. Your goal is to keep tasks short enough to stay under the 16ms frame budget for a smooth 60fps experience.
Find the bottleneck, then fix it.
Fix the most common problems: rendering and input
In most machine coding interviews, performance issues are deliberately designed around rendering. The interviewer wants to see if you can handle expensive rendering, frequent events, or large lists.
Control event frequency with debounce and throttle
A user can trigger hundreds of events per second by typing, scrolling, or resizing a window. Firing a heavy function on every event will kill performance.
Debounce: Use this when you only care about the final event in a series. A classic example is a search input. You don't want to fire an API request for every keystroke, only after the user has paused typing.
Throttle: Use this when you want to handle an event periodically during a series. For example, updating a scroll-position indicator. You want to update it as the user scrolls, but not hundreds of times per second. Once every 100ms is enough.
When an interviewer asks you to build a typeahead search, they are not just testing your API fetching skills. They are testing if you know to debounce the input. Not doing so is a major red flag.
Here is the fundamental difference:
This is a standard, interview-ready debounce implementation. You should be able to write this from memory.
function debounce<T extends (...args: any[]) => void>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Render huge lists with virtualization
If a problem involves "a large list of items," your first thought must be virtualization (also called windowing). Rendering thousands of DOM nodes at once is a guaranteed way to fail a performance interview.
Virtualization only renders the items currently visible in the viewport, plus a small buffer. As the user scrolls, it recycles the DOM nodes, replacing the content of nodes that scroll out of view with the content of items scrolling into view.
You don't need to implement this from scratch in a 45-minute interview. Name a library like react-window or tanstack-virtual and explain the concept. That's enough.
Prevent needless re-renders with memoization
In React, a component re-renders if its state changes, its parent re-renders, or its context value changes. Memoization is a way to skip re-renders when the props haven't changed.
React.memo(): A higher-order component that wraps a component, preventing it from re-rendering if its props are shallowly equal to the previous props.useMemo(): Caches the result of an expensive calculation. The calculation only re-runs if one of its dependencies changes.useCallback(): Caches a function definition. This is important when passing callbacks to memoized child components, as it prevents the child from re-rendering just because the parent created a new function instance.
The trap: Over-memoizing. Wrapping every function in useCallback is a code smell. Explain that you use it specifically to preserve referential equality for dependencies of hooks (useEffect, useMemo) or for props passed to a component wrapped in React.memo.
Unblock the main thread
If your UI freezes, it's because a long-running JavaScript task is blocking the main thread. The browser can't paint new frames or respond to user input until the task is done.
Offload heavy work to a Web Worker
For truly CPU-intensive tasks—like complex calculations, data processing on a large client-side dataset, or image manipulation—use a Web Worker. A worker runs on a separate background thread.
The trade-off is complexity. Communication with the worker is asynchronous via postMessage and onmessage. You can't directly access the DOM from a worker. Mentioning Web Workers shows you know how to handle computation that would otherwise block the UI.
Avoid layout thrashing with requestAnimationFrame
Layout thrashing happens when you alternate between reading from and writing to the DOM in a loop. Each time you read a property like offsetHeight after a write, you force the browser to perform a synchronous reflow to give you the up-to-date value.
// BAD: Causes layout thrashing
elements.forEach(el => {
const width = container.offsetWidth; // READ
el.style.width = (width / 2) + 'px'; // WRITE
});
To fix this, batch your reads and then batch your writes. For animations or frequent updates, requestAnimationFrame is the perfect tool. It schedules your function to run just before the browser's next repaint, ensuring all your DOM manipulations happen together efficiently.
Make it feel fast
Sometimes, you can't make the work faster, but you can improve the user's perception of performance.
Optimistic UI: When a user performs an action (e.g., clicking "like"), update the UI immediately, assuming the network request will succeed. Handle the server confirmation in the background. If it fails, roll back the change and show an error. This makes the application feel instantaneous.
Lazy Loading: Don't load everything at once.
- Components: Use
React.lazyandSuspenseto load components only when they are needed (e.g., for a new route or a modal that hasn't been opened). This is critical for reducing initial bundle size. - Images: Use the native
loading="lazy"attribute on<img>tags for images that are below the fold. The browser will handle the rest.
Try it
Implement a useDebounce hook. Apply it to a search input that filters a local array of 1,000 objects. Notice the difference in responsiveness as you type.
Next: Complex State Management & Architecture
Lock it in — apply this lesson under interview conditions.