JavaScript Concurrency and React's useState vs useRef
System DesignModel answerLast updated
Explain how JavaScript achieves concurrency on a single thread, when real parallelism is possible, and how useState and useRef differ in a React component.
JavaScript Concurrency and React Hook Semantics
This question covers two tightly related fundamentals: how JavaScript actually runs code, and how React decides when to re-render.
Part 1 — JavaScript's execution model
- Describe how JavaScript executes code in the browser or in Node.js. Is execution single-threaded or multi-threaded?
- How does JavaScript handle multiple things happening "at the same time" (timers firing, network responses arriving, user clicks) without multiple threads?
- What are Web Workers (browser) and
worker_threads(Node.js)? When would you reach for them, and what are their practical limitations?
Part 2 — useState vs useRef in React
- What does
useStatedo, and what happens to the component when you call the state setter? - What does
useRefreturn, and how does mutatingref.currentdiffer from calling a state setter? - Walk through the trade-offs and give concrete examples of when you'd pick one over the other.
Aim your explanation at a junior engineer who understands basic React but has never thought carefully about the event loop or hook internals.
Hints
Hint 1
Think about the difference between concurrency (many things in progress) and parallelism (many things executing simultaneously) — JavaScript achieves one but not the other on the main thread.
Hint 2
For useState, ask yourself: when does the component actually see the new value, and what happens if you log the variable immediately after calling the setter?
Hint 3
The clearest rule for the hooks choice: if the value appears somewhere in the JSX, it belongs in state; if it's just bookkeeping the render doesn't care about, a ref is the right tool.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — JavaScript's Execution Model
Single thread, not single-tasking
JavaScript has one call stack. Only one function executes at any moment, and every function runs to completion before anything else can start — this is called run-to-completion semantics. There is no pre-emption: no other JS code can interrupt a running function.
That sounds limiting, but it works well in practice because most of what JavaScript waits on — network responses, timers, disk reads, user input — happens outside the JS thread. The browser and Node.js (via libuv) handle that work natively and push a callback onto a queue when it finishes. The event loop picks those callbacks up one at a time.
The event loop in detail
Each iteration of the loop does roughly this:
- Pull one macrotask off the task queue and run it to completion. Macrotasks include
setTimeout/setIntervalcallbacks, I/O events, and UI events likeclick. - Drain the microtask queue entirely. Every resolved Promise
.then, everyawaitcontinuation, and everyqueueMicrotaskcall runs here — all of them, before the loop moves on. - In the browser, possibly render: style recalculation, layout, and paint.
requestAnimationFramecallbacks run just before the paint step. - Repeat.
console.log('A');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('microtask'));
console.log('B');
// Output: A B microtask timeout
This is why microtasks (Promises) always resolve before the next setTimeout, even a zero-millisecond one.
Node.js differences: libuv adds phases (timers → I/O callbacks → poll → check with setImmediate → close). process.nextTick callbacks drain before Promise microtasks. File system operations, dns.lookup, and some crypto/zlib work run on a libuv thread pool (4 threads by default, tunable via UV_THREADPOOL_SIZE), but the callbacks still return to the single JS thread.
Concurrency vs. parallelism
async/await is syntactic sugar over Promises. An await yields back to the event loop — it does not spawn a thread. This gives you concurrency (many operations in flight) but not parallelism (many operations computing simultaneously).
The practical implication: a CPU-heavy loop blocks everything. In a browser, no clicks or frames render until the loop finishes. In Node, every pending request waits. This model is great for I/O-bound workloads and bad for CPU-bound ones.
Real parallelism: workers
Browser — Web Workers: a Worker runs a script on a separate OS thread with its own event loop and global scope. Key constraints:
- No DOM access — no
window, nodocument. All UI changes must be posted back to the main thread. - Communication via
postMessage. Data is copied by the structured-clone algorithm, which costs time for large objects. Functions cannot be transferred. - Large binary buffers (
ArrayBuffer,OffscreenCanvas) can be transferred with zero copy; the sender loses access after transfer. - True shared memory with
SharedArrayBuffer+Atomicsis possible but requires cross-origin isolation headers (COOP/COEP) and reintroduces race conditions.
Node.js — worker_threads: same mental model as Web Workers. child_process / cluster go further by spawning separate processes, which is how Node servers fully utilize multiple CPU cores.
When workers are worth it: image processing, parsing large files, crypto, and compression. Startup cost per worker is non-trivial (separate V8 isolate and heap), so pool workers rather than spawning one per task.
Part 2 — useState vs useRef
useState — values that drive the UI
const [count, setCount] = useState(0);
Calling the setter does two things: it queues the new value and schedules a re-render. The component does not see the new value in the current render — count is a constant for the current render (a snapshot). This is the most common source of confusion:
setCount(count + 1);
console.log(count); // still the old value
In React 18+, multiple setter calls within the same event are batched into one render. When the new value depends on the previous one, use the functional form to avoid lost updates:
setCount(c => c + 1);
React bails out of a re-render if the new value is Object.is-equal to the old one. Never mutate state objects directly — always replace them (setUser({ ...user, name: 'Alice' })).
useRef — a mutable container that doesn't trigger renders
const ref = useRef(initialValue); // → { current: initialValue }
React returns the same object on every render for the component's lifetime. Writing to ref.current is synchronous and immediate, and it does not schedule a re-render. Reading ref.current always gives the latest value — there is no snapshot concept.
The most common use is holding a DOM node:
<input ref={inputRef} />
// then in an effect or handler:
inputRef.current.focus();
One important rule: don't read or write ref.current during render. Rendering should be a pure function of props and state. Use refs inside effects and event handlers.
Side-by-side comparison
useState | useRef | |
|---|---|---|
| Persists across renders | Yes | Yes |
| Triggers re-render on change | Yes | No |
| Update timing | Batched, scheduled | Synchronous, immediate |
| Value in a stale closure | Snapshot from that render | Always latest |
| Primary use | Data shown in the JSX | DOM handles and bookkeeping |
Choosing between them
The one-sentence rule: if changing the value should change what appears on screen, use state. If it's bookkeeping the render doesn't care about, use a ref.
Use useState for: form field values, modal open/closed toggles, fetched data, loading and error flags, counters, selected items.
Use useRef for: DOM node handles (focus, scroll, measure), interval/timeout IDs, AbortController instances, tracking "has this effect run before?" flags, and capturing the latest version of a prop or callback inside a long-lived listener to avoid stale closures.
function Stopwatch() {
const [elapsed, setElapsed] = useState(0); // renders → state
const intervalRef = useRef(null); // ID doesn't render → ref
const start = () => {
intervalRef.current = setInterval(
() => setElapsed(e => e + 1),
1000
);
};
const stop = () => clearInterval(intervalRef.current);
return (
<div>
<p>{elapsed}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}
Common mistakes to call out
- Expecting
useStateto update synchronously and reading the variable right after the setter call. - Storing UI-relevant data in a ref and wondering why the component doesn't re-render.
- Mutating a state object directly (
user.name = 'Alice') instead of replacing it. - Spawning a new Web Worker per task instead of maintaining a pool, paying startup cost repeatedly.
- Assuming
async/awaitadds threads — it does not.