Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React createElement vs cloneElement

Can anyone let me know if using cloneElement (on exist element instance) or createElement (on react Element class) which one is better in term of performance?

Sometimes cloning something is faster than create new instance. Please let me know. Thanks

like image 830
James Avatar asked Feb 25 '16 00:02

James


People also ask

Should you use React cloneElement?

React. cloneElement() is useful when you want to add or modify the props of a parent component's children while avoiding unnecessary duplicate code.

What is the use of React createElement?

createElement()Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span' ), a React component type (a class or a function), or a React fragment type.

What is cloneElement?

cloneElement lets you create a new React element using another element as a starting point.


1 Answers

Using cloneElement will be usually be faster because you only need to instantiate one initial component.

This jsperf test shows cloneElement to be nearly twice as fast as createElement for Chromium 45 on Linux:

  • cloneElement ~1.7m ops/second
  • createElement ~0.85m ops/second

If you have a base component that you can clone without changing, then using cloneElement is a clear choice, both semantically and in terms of performance.

like image 88
Dan Prince Avatar answered Oct 20 '22 05:10

Dan Prince