Search⌘ K

React favours composition over inheritance

Explore the concept of composition versus inheritance in React and JavaScript classes. Understand why composition, which uses the HAS-A principle, offers more flexibility and reusability than inheritance's IS-A principle. This lesson helps you grasp how composition avoids common pitfalls like code duplication and improves adaptability in your React projects.

We'll cover the following...

Why not inheritance?

Imagine you are making a video game and need two characters: one that can shoot lasers and another that can cast spells. Both characters have a name and health.

You solve this problem neatly with inheritance. As per the following, a class structure with one parent class, the character, and two child classes called caster and shooter can be created.

Node.js
class Character {
constructor(name){
this.name = name;
this.health = 100;
}
}
class Shooter extends Character{
constructor(name){
super(name);
}
shoot(){
console.log(`${this.name}: prepare to die!`);
this.health--;
}
getHealth(){
console.log(this.health);
}
}
class Caster extends Character{
constructor(name){
super(name);
}
cast(){
console.log(`${this.name}: Avada Kedavra!`);
this.health--;
}
getHealth(){
console.log(this.health);
}
}
Dumbledore = new Caster("Albus Percival Wulfric Brian Dumbledore")
Dumbledore.cast();
DarthVader = new Shooter("Anakin Skywalker");
DarthVader.shoot();

Suppose you launched your game and it was a big hit. But now, your game’s buyers demand another character that can both shoot lasers and cast spells.

There are two things you can do:

  1. Make the shoot() and cast() functions a part of the parent Character class and have the ShooterFighter class inherit it. The only problem with this is
...