⚛️ React.js Intermediate

What is the difference between React.cloneElement and React.createElement?

Answer

React.createElement(type, props, ...children) creates a new React element from scratch — it is what JSX compiles to. <Button color="blue">Click</Button> becomes React.createElement(Button, { color: "blue" }, "Click"). You rarely call it directly. React.cloneElement(element, newProps, ...newChildren) creates a new element based on an existing React element, merging new props with the existing ones. Useful when a parent wants to add or override props on children it receives: function Toolbar({ children }) { return React.Children.map(children, child => React.cloneElement(child, { className: "toolbar-item" })); }. This adds a className to every child without the child having to know about it. Common use cases for cloneElement: adding event handlers to children (RadioGroup adding onChange to Radio children), injecting context-based props, building compound components. Caution: cloneElement is fragile — it couples the parent to the children's props interface. Modern alternatives using Context or render props are often more maintainable. React 19 may deprecate cloneElement patterns in favor of Context.