Yuan's Blog
EN

Detailed Explanations of Common React Interview Questions

React Fundamentals

  1. What is a pure function? Why should React function components be pure?

    • A pure function produces the same output given the same input and causes no side effects. It does not modify anything outside its own scope.
    • If a function is impure, the UI can become unstable or unpredictable, leading to render outputs that differ from what you expect.
  2. What is JSX? Why use JSX?

    • JSX stands for JavaScript XML. It allows you to write markup and logic together in a unified, expressive syntax.
    • Key JSX rules:
      • Must return a single root element: If a component needs to return multiple elements, wrap them in a parent element (e.g., <div> or fragments <> ... </>).
      • All tags must be closed: For example, <img> must be written as <img />.
      • Most attribute names use camelCase.
  3. Explain the React lifecycle.

    • Class Components provide the older, traditional lifecycle methods.
class MyComponent extends React.Component {
  render() {
    return <div>Hello</div>;
  }
}
  • Function Component — the modern mainstream approach in React.
function MyComponent() {
  return <div>Hello</div>;
}
  • React components have three core lifecycle phases: Mounting, Updating, and Unmounting.
    • During Mounting, the sequence is: constructorrendercomponentDidMount.

    • During Updating, when props or state change, React triggers render, and after the update completes, componentDidUpdate runs.

    • During Unmounting, componentWillUnmount runs to perform cleanup.

    • The entire process is split into the Render phase and the Commit phase: The Render phase is purely computational and must not contain side effects; the Commit phase applies DOM changes and runs lifecycle side-effect methods.

    • Functional Components do not have these lifecycle methods, but they use useEffect to cover mount/update/unmount side-effect scenarios.

  1. What is the Virtual DOM?

    • The DOM (Document Object Model) is a tree structure created by the browser after parsing HTML. HTML itself is just text; after parsing, the browser transforms it into a node tree where each tag, text, and attribute becomes a Node object. JavaScript can then read, modify, insert, or remove nodes.
    • The Virtual DOM is an in-memory JavaScript object tree that represents the structure of the real DOM. Because it is just plain objects, creating and diffing it is very fast.
    • The benefit of using a Virtual DOM is that React can use declarative UI. Developers don’t manually manipulate the DOM; instead, they update state to describe what the UI should look like. React ensures the DOM stays in sync with the state.
    • During rendering, React generates a Virtual DOM, compares it with the previous Virtual DOM (diffing), and updates only the parts that have changed.
  2. What are React Hooks?

    • What is a Hook? A Hook is a mechanism that extracts “state logic” and “side-effect logic” from classes and gives function components the capabilities they previously lacked.
      • useState — the smallest unit for state management.
const [count, setCount] = useState(0);

<button onClick={() => setCount(count + 1)}>{count}</button>
  • useEffect — handles side effects (asynchronous operations, subscriptions, events, DOM manipulation).
useEffect(() => {
  const id = setInterval(() => console.log("tick"), 1000);
  return () => clearInterval(id);
}, []);
  • useLayoutEffect — a side-effect hook that runs earlier in the commit cycle.
useLayoutEffect(() => {
  const rect = ref.current.getBoundingClientRect();
  console.log(rect);
});
  • useReducer — used to manage more complex state logic.
function reducer(state, action) {
  switch (action.type) {
    case 'inc':
      return { count: state.count + 1 };
    default:
      return state;
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0 });

<button onClick={() => dispatch({ type: 'inc' })}>
  {state.count}
</button>
  • useCallback — keeps a function’s reference stable as long as its dependencies do not change, preventing unnecessary re-renders and repeated side effects.It creates the function on the component’s first render and reuses the same reference on all subsequent renders.
const handleClick = useCallback(() => {
  console.log("clicked");
}, []);
  • useMemo — re-computes a value only when its dependencies change; otherwise it reuses the previous result. Useful for preventing expensive operations (like repeated filter + sort) from running on every render.
const total = useMemo(() => {
  return items.reduce((sum, v) => sum + v, 0);
}, [items]);
  • useRef — stores a mutable value that persists across renders, and changing it does not trigger a re-render.
const inputRef = useRef();

useEffect(() => {
  inputRef.current.focus();
}, []);
  1. Why must Hooks be called at the top level? Explain using the implementation idea of useState.

    • If Hooks were called inside if...else blocks, loops, or nested functions, the call order would change across renders. React relies on a stable calling order to know which state belongs to which Hook. If the order changes, React has no way to match a Hook call to the correct stored state, causing the state mapping to break.
    • Hooks are bound by call order, not by variable names. As long as the order is unstable, the internal state mapping will be corrupted. This is why Hooks must always be called at the top level of a component.
  2. Explain useEffect. What is the difference between useEffect and useLayoutEffect?

    • useEffect: runs after the screen is painted. Suitable for logic that can occur later—slower operations that do not affect the initial visual layout.
    • useLayoutEffect: runs before the browser paints the screen. Ideal for logic that must run early, especially anything related to layout measurements or DOM adjustments.
  3. Why does React require key when rendering a list?

    • React updates a list by reusing existing nodes, not by rebuilding everything. To reuse nodes correctly, React must answer: “Which old node corresponds to the new element at position X?” React cannot know this automatically. Array positions are unreliable because insertions/removals shift the indices. So React needs a stable identity: the key.
    • Why you should not use the array index as key: Insert/remove will shift all indices → React thinks all items changed → unnecessary DOM reconstruction.
  4. Why does state in React need to be updated immutably? What is immutability and how do you write immutable code?

    • Immutable = do not modify the original object/array; instead, create a new one. Mutable = modify the existing object directly.
    • The key difference: whether a new reference is created. React only detects updates when the reference changes.
    • The spread operator (...) is one of the most common tools for creating immutable copies.
    • JavaScript’s common immutable array operations:
      • Add elements: slice (to copy) + spread
      • Remove elements: filter
      • Modify elements: map