Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Morokhovskyi Roman
Morokhovskyi Roman

Posted on • Edited on

     

React 18 killer feature

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"));
Enter fullscreen modeExit fullscreen mode

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    });}
Enter fullscreen modeExit fullscreen mode

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 />);
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Developer
  • Location
    Ukraine
  • Joined

More fromMorokhovskyi Roman

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp