Inheritance in React Components
In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a superclass is called a subclass or derived class.
React has a powerful composition model, and is recommend to use composition instead of inheritance to reuse code between components. However, there can be cases where inheritance is preferred to composition like reusing a particular functionality of a component than the component itself.
In JavaScript, one of the ways to leverage inheritance is using extends
keyword on the constructor function. Function that gets extended is the superclass class while the one extending is the subclass.
Conventional approach in React
We extends
React’s Component to access functions defined on the prototype object of Component constructor. This allows us to call setState()
from any of the class component we create, traversing the prototype chain.
The same approach can be extended to create our own inheritance inside the component tree. Let us quickly go over different ways we define function inside Component.
- Arrow functions: The most sought after way to define function considering easiness to get the correct
this
context. However, this has a downside as the function gets copied to each of the child instance. - Conventional function definition: This is not typically used as it requires to create correct
this
binding in the constructor function so as to getthis
context inside the function. However, the main advantage of using this approach is the functions are defined in the prototype object of the constructor and is referenced through prototype chain.
Let us see this in action inside a React Component.
Here, doNothing()
is defined as arrow function and checkBindings()
uses conventional function definition approach.
Here, we have extended App instead of Component and are able to access the functions defined in the superclass App through inheritance. doNothing()
gets copied to the instance of ChildValue
while checkBindings()
is accessible through prototype chain.
checkBindings as Prototype object
Conventional function definition approach needs to be followed if we intend to share functionalities between different components in our react tree.
If you liked reading this, don’t forget to clap. 👏👏
You can also follow me on twitter @Akash940 for JavaScript or React updates.
Thank-you!