šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React performance tip – use ReactDOM.createRoot() instead of ReactDOM.render()

The ReactDOM.createRoot() comes as a replacement for the ReactDOM.render().

Among multiple other benefits using the createRoot ads the automatic batching of multiple setState() calls. This reduces the number of render cycles a component needs, therefore improving performance.

For example, let's take the below React component:

const MyComponent = ({descriptor}) => {
  const [count, setCount] = useState(0)
  const [flag, setFlag] = useState(false)
  const renders = useRef(0)

  useEffect( () => {renders.current++})

  const onClickHandler = ()=> {
    Promise.resolve(100).then(
      ()=> {
        setCount(c => c+1)
        setFlag(f => !f)
      }
    )
  }

  return(<>
      <p>{descriptor} renders = {renders.current}</p>
      <button onClick={onClickHandler}>Add ({count})</button>
  </>)
}

The component makes 2 asynchronous calls to setState() and tracks the total number of how many times that React component rerendered.

It looks like this:
performance ReactDOM.createRoot() vs ReactDOM.render()

Now, lets render this component both with ReactDOM.createRoot() and ReactDOM.render():

// rendering the compoent with render()
ReactDOM.render(
  <MyComponent descriptor="ReactDOM.render()" />, 
  document.getElementById("id1")
)

// rendering the compoent with createRoot()
const root = ReactDOM.createRoot(document.getElementById("id2"))
root.render(<MyComponent descriptor="ReactDOM.createRoot()" />)

Even if we have the exact same component, using ReactDOM.createRoot() will result in 50% fewer renderings, as it batches multiple async setStates calls.
performance ReactDOM.createRoot() vs ReactDOM.render()

You can checkout the full codepen with this example here.

In conclusion, using ReactDOM.createRoot() instead of ReactDOM.render() can greatly improve the performance of your React application and as demonstrated in the example, it can result in fewer render cycles.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *