Created
November 15, 2021 23:00
-
-
Save harshaktg/9a38f44cf85f27164ca1975bb9083e0c to your computer and use it in GitHub Desktop.
React 18 auto batching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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