Skip to content

Instantly share code, notes, and snippets.

@lalunamel
Last active May 11, 2024 01:21
Show Gist options
  • Save lalunamel/7d2fe2eed759e19a42c664c9c8dadbad to your computer and use it in GitHub Desktop.
Save lalunamel/7d2fe2eed759e19a42c664c9c8dadbad to your computer and use it in GitHub Desktop.
How does React's act work?

How does React's act work?

tl;dr: It wraps some work you'd like to do and waits for that work to complete before returning

Why do I get this error?

An update to Component inside a test was not wrapped in act(...).

tl;dr: A React component is updating (probably as a result of changing state, props, or hooks) but that update is not happening inside of something wrapped in act.

  • Implemented in ReactFiberWorkLoop
  • That error is produced when running react in a test environment (not sure how it knows this tbh) and actQueue is null (actQueue is set when act is called)
  • Produced while calling scheduleUpdateOnFiber, which is ?probably? called as a result of changing state or props

Details

Here is where act is implemented. React Testing Library calls act for you when calling render as well as when calling fireEvent (this and this)

FYI - act is only callable in developer mode - otherwise it will throw an exception

  1. act creates a new actQueue or uses the current one if it exists already
  2. then it calls the block passed in (the code you're wrapping in act)
    • that passed in block does the work you specified in your test
    • that work causes state and props to update, and eventually ReactFiberRootScheduler.scheduleCallback is called by react, which pushes work onto the act actQueue
  3. then it flushes the current actQueue by executing every work item in it
  4. then it sets actQueue = null (here for synchronous callbacks, here for async callbacks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment