šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

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.

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

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