HeadlinesBriefing favicon HeadlinesBriefing.com

React's Composition Over Inheritance

DEV Community •
×

React's official documentation states it has found no use cases for component inheritance hierarchies across thousands of components. This contradicts traditional object-oriented programming taught in Java or C++, where inheritance is standard. React's core principle favors composition over inheritance, building complex components by combining simpler ones rather than creating deep class hierarchies.

Inheritance creates rigid 'is-a' relationships, like a Dog class extending an Animal class. This becomes problematic when you need to mix behaviors, such as creating a FlyingDog that needs to bark and fly. JavaScript doesn't support multiple inheritance, forcing developers into messy hierarchies. Composition, however, uses 'has-a' relationships, allowing flexible mixing of behaviors like canEat, canBark, and canFly functions.

React's component model is built around composition patterns. The modern approach uses functional components and props, not class extension. For example, instead of a PrimaryButton class extending BaseButton, you create a Button component and compose it with specific props. This avoids tight coupling, improves reusability, and makes components easier to test and maintain. The children prop is a key pattern for containment, letting components render whatever content is passed to them without knowing its structure.