Capítulo 72 de 116

Chapter 72: act

Core Idea

act(callback) is a testing utility that ensures all state updates, Effects, and other queued React work triggered inside callback finish processing before assertions run — the mechanism most testing libraries (React Testing Library, etc.) already wrap around your interactions internally.

Key Concepts

  • What it solves: React batches and schedules updates; without act, a test might assert on the DOM before an Effect-triggered state update has actually applied, producing a flaky or wrong assertion.
  • Typical usage is indirect: most projects use React Testing Library or similar, which calls act internally around render()/fireEvent()/userEvent calls — writing a raw act(() => {...}) by hand is uncommon except when testing outside those helpers or with lower-level test utilities.
  • Async version: await act(async () => { ... }) flushes microtask-queued updates (e.g. from a resolved promise inside an event handler) as well, not just synchronous ones.
  • Test-only tool: act has no role in application code — it exists purely to make test assertions deterministic against React's internal scheduling.

Key Takeaways

  1. If you're using React Testing Library or similar, you're already benefiting from act without calling it directly — reach for it explicitly mainly when writing lower-level custom test utilities.
  2. A test failing with an "update not wrapped in act" warning means an assertion ran before React finished processing an update — the fix is ensuring the triggering interaction is properly wrapped, not silencing the warning.
  3. act is exclusively a testing tool — never import or use it in production application code.

Connects To

  • Ch 53 (useEffect): the async, scheduled work act ensures has settled before assertions run.