KatInterview

JavaScript Concurrency and React's useState vs useRef

System DesignModel answer
HardModel answerSystem Designjavascriptreactconcurrency

Last 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 useState do, and what happens to the component when you call the state setter?
  • What does useRef return, and how does mutating ref.current differ 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.