Probably you already heard about the release React v18.0
I wish to introduce you to a new killer feature of the release.
Let’s take a look at this example.
importReact,{useState,useEffect}from"react";importReactDOMfrom"react-dom";asyncfunctionfetchSomething(){awaitnewPromise((res,rej)=>{setTimeout(res,100);});}functionCounter({count,flag}){useEffect(()=>{console.log("render Counter");});return<h1style={{color:flag?"blue":"black"}}>{count}</h1>;}functionApp(){const[count,setCount]=useState(0);const[flag,setFlag]=useState(false);useEffect(()=>{console.log("render App");});functionhandleClick(){setCount((c)=>c+1);setFlag((f)=>!f);}return(<divid="ttt"><buttonid="b"onClick={handleClick}>Next</button><Countercount={count}flag={flag}/></div>);}ReactDOM.render(<App/>,document.querySelector("#container"));
Just one button counter. AndhandleClick
handler set state for flag and count.
React is smart lib and intentionally doesn't render components twice, despite in the handler we update state twice. Because React batches event handlers.
But what if we a bit changehandleClick
function and add some async magic here
async function fetchSomething() { await new Promise((res, rej) => { setTimeout(res, 100); });}function handleClick() { fetchSomething().then(() => { setCount((c) => c + 1); // Causes a re-render setFlag((f) => !f); // Causes a re-render });}
And if you run again the code, you most probably came across with double rendering components,useEffect
tells you in the console. This is because React can't batch state changes. What is the reason? Asynchronous handlers runafter the event in a callback, notduring. Obviously, all async operation is non-blocking and executes after the main stack.
In React 18 this issue is solved, you just need to replace in the codeReactDOM.render
toReactDOM.createRoot
ReactDOM.createRoot(document.querySelector("#container")).render(<App />);
createRoot enablesConcurrent Mode. Now your application can be more productive and doesn't trigger re-rendering after each state changes within one event handler, which is great!
This is howAutomatic batching render feature works.
I Hope, I brought you some useful content.
Follow me on 🐦Twitter if you want to see more content.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse