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?
React. cloneElement() is useful when you want to add or modify the props of a parent component's children while avoiding unnecessary duplicate code.
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.
cloneElement lets you create a new React element using another element as a starting point.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With