As explained in this question, React batches state update calls within React event handlers.
React currently will batch state updates if they're triggered from within a React-based event, like a button click or input change. It will not batch updates if they're triggered outside of a React event handler, like an async call.
I.e., a setFoo
and setBar
would be fused together when called from a React event handler callback.
I'm dealing with various third party libraries, some of them wrap non-React JS libraries. I'm passing them callbacks, and I'm wondering whether these callbacks fall under the "React event handler" category, i.e., whether state update batching applies for them.
Is there a way to manually check if state update are batched, or equivalently, whether some code is executed within a React event handler? I'm thinking about a temporary check like:
let callback = () => {
// fictitious checks
console.log(ReactDOM.checkIfUpdatesAreBatched());
console.log(ReactDOM.checkIfRunningInReactEventHandler());
setFoo("foo");
setBar("bar");
}
Edit: The reason I don't want to know this is to make sure that Foo
and Bar
updates are atomic for consistency reasons. Of course I can fuse the state together, but this has performance issues because a setFooAndBar
triggers too many components to re-render, which of course could be mitigated by further memoizing... If I could prove that setFoo
and setBar
always run with update batching the state separation would be sound.