Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.cloneElement memory efficiency

Tags:

reactjs

Is the originalComponent garbage collected if I have:

const WrapperComponent = ({ originalComponent, ...props }) => {
  const clone = React.cloneElement(originalComponent, props);
  return <div>{clone}</div>;
};

Or does it lead to the duplication of components?

like image 921
ingelity Avatar asked Aug 10 '17 18:08

ingelity


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 difference between createElement and cloneElement?

createElement is the code that JSX gets compiled or converted into and is used by reacting to create elements. cloneElement is used for cloning elements and passing them new props. This method is used to describe how the User Interface looks. This method is used to manipulate the elements.

What is cloneElement?

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

What is createElement in React?

createElement() React. createElement( type, [props], [... children] ) 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.


1 Answers

There is no memory inefficiency to using React.cloneElement(). It creates a new React element, using the original as the base. As with all objects, unless a reference is kept to the original element in a variable somewhere, it will get garbage collected and deleted.

To verify this I did a quick test using the Chrome dev tools memory snapshot profiler. Rendering a single component using your WrapperComponent results in only one instance of the cloned component to be in memory.

like image 148
jered Avatar answered Oct 05 '22 06:10

jered