React State Batching and Functional Updates: What Changes in React 18

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 1

Batching & Re-render Quiz

Three questions on React 18 automatic batching — how many renders fire from event handlers, async callbacks, and flushSync.

1
const [a, setA] = useState(0);
const [b, setB] = useState(0);

function handleClick() {
  setA(1);
  setB(2);
}

How many re-renders does one button click cause in React 18?

2
// React 17 behavior
fetch('/api').then(() => {
  setLoading(false);
  setData(result);
  // How many re-renders in React 17?
});

In React 17, how many re-renders do these two setters cause inside a Promise callback?

3
import { flushSync } from 'react-dom';

function handleClick() {
  flushSync(() => setCount(c => c + 1));
  // After this line, DOM is already updated
  flushSync(() => setFlag(true));
}

How many re-renders does this cause?

0/3 answered

💡 React 18 automatic batching: all updates (event handlers, async callbacks, timeouts) are batched into one render by default. flushSync is the escape hatch when you need a synchronous flush.

Practice: React State Batching and Functional Updates: What Changes in React 18 — Interactive Exercises | Durgesh Rai