DEV Community

Morokhovskyi Roman
Morokhovskyi Roman

Posted on • Updated 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.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

async function fetchSomething() {
  await new Promise((res, rej) => {
    setTimeout(res, 100);
  });
}

function Counter({ count, flag }) {
  useEffect(() => {
    console.log("render Counter");
  });
  return <h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>;
}

function App() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

  useEffect(() => {
    console.log("render App");
  });

  function handleClick() {
    setCount((c) => c + 1);
    setFlag((f) => !f);
  }

  return (
    <div id="ttt">
      <button id="b" onClick={handleClick}>
        Next
      </button>
      <Counter count={count} flag={flag} />
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector("#container"));
Enter fullscreen mode Exit fullscreen mode

Just one button counter. And handleClick 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 change handleClick 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 mode Exit 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 run after the event in a callback, not during. 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 code ReactDOM.render to ReactDOM.createRoot

ReactDOM.createRoot(document.querySelector("#container")).render(<App />);
Enter fullscreen mode Exit fullscreen mode

createRoot enables Concurrent 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 how Automatic 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)