Component Patterns — Series 2

Preview — 3 of 10 questions

If roomId changes from "general" to "random", what is the exact console output order?

javascript
function ChatRoom({ roomId }) {
  useEffect(() => {
    console.log(`Connecting to ${roomId}`);
    const connection = createConnection(roomId);
    connection.connect();
    return () => {
      console.log(`Disconnecting from ${roomId}`);
      connection.disconnect();
    };
  }, [roomId]);

  return <h1>Room: {roomId}</h1>;
}
AConnecting to random, then Connecting to general — React connects to the new room first, then cleans up the old one afterward
BDisconnecting from general only — cleanup runs, but the new effect doesn't run again since roomId is just a prop, not state
CDisconnecting from general, then Connecting to random — the cleanup for the previous render's effect always runs before the new effect for the current render
DConnecting to random only — the disconnect cleanup is skipped when roomId changes, and only fires on unmount

Whats the problem with computing `expensiveCount` this way, and whats the better approach?

javascript
function ProductList({ products }) {
  const [expensiveCount, setExpensiveCount] = useState(0);

  useEffect(() => {
    setExpensiveCount(products.filter(p => p.price > 100).length);
  }, [products]);

  return <p>{expensiveCount} expensive products</p>;
}
AexpensiveCount should just be computed directly during render — const expensiveCount = products.filter(p => p.price > 100).length; — no useState/useEffect needed at all, since it's fully derivable from products every render
BThis code is correct and idiomatic — useEffect is the standard way to keep any value in sync with props
CThe bug is that useEffect runs before the DOM updates, so expensiveCount would always be one render behind
Dproducts.filter mutates the original array, which is the real problem here, unrelated to where the count is stored

EditForm and ViewMode both happen to render a top-level <div>. When isEditing flips from true to false, what does React do with the internal state/DOM of the previously-rendered component?

javascript
function Panel({ isEditing }) {
  return isEditing ? <EditForm /> : <ViewMode />;
}
AReact reuses the same DOM node and internal state, since both components render the same root tag (<div>) at the same position in the tree
BReact throws an error, since two different component types can't occupy the same conditional branch
CReact preserves state only for the props that are named identically between EditForm and ViewMode
DReact unmounts the previous component entirely (discarding its internal state, running any cleanup) and mounts the new one fresh, because reconciliation compares component type at each position, not just the rendered tag name

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.