React & Modern Frontend (445 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)
Why are you not required to use inheritance?
In React, it is recommended to use composition over inheritance to reuse code between components. Both Props and composition give you all the flexibility you need to customize a component’s look and behavior explicitly and safely. Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript module. Later components import it and use that function, object, or class, without extending it.
Practical Code Example
jsx
// Composition over Inheritance: Specialized components wrap generic components
function Dialog({ title, children }) {
return <div className="dialog"><h2>{title}</h2>{children}</div>;
}
function WelcomeDialog() {
return <Dialog title="Welcome"><p>Thank you for visiting!</p></Dialog>;
}