Skip to content

Instantly share code, notes, and snippets.

@harshaktg
Created November 15, 2021 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harshaktg/9a38f44cf85f27164ca1975bb9083e0c to your computer and use it in GitHub Desktop.
Save harshaktg/9a38f44cf85f27164ca1975bb9083e0c to your computer and use it in GitHub Desktop.
React 18 auto batching
import { useState, useLayoutEffect } from "react";
import * as ReactDOM from "react-dom";
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
console.log("=== click ===");
fetchSomething().then(() => {
// React 18 with createRoot batches these:
setCount((c) => c + 1); // Does not re-render yet
setFlag((f) => !f); // Does not re-render yet
// React will only re-render once at the end (that's batching!)
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
<LogEvents />
</div>
);
}
function LogEvents(props) {
useLayoutEffect(() => {
console.log("Commit");
});
console.log("Render");
return null;
}
function fetchSomething() {
return new Promise((resolve) => setTimeout(resolve, 100));
}
const rootElement = document.getElementById("root");
// This opts into the new behavior!
ReactDOM.createRoot(rootElement).render(<App />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment