Composition Over Inheritance in React

React brings an OOP approach along with some functional programming best practices to front end engineering on the web.

It is not the only library to offer composable components as a central feature in developing your Javascript Front End, but it is definitely the most used solution today.
One thing that makes React unique is how close it is to just Javascript.
This makes it easier to compose a layout in programmatic fashion, opening us to greater utilization of programming paradigms like OOP, FP.

Given the class structure of react components (or containers in a two dimensional smart vs dumb UI component structure), one is left with many of the usual OOP concerns when crafting their program.
One such concern is the concept of composition vs inheritance.
This is essentially a design choice, whereby the developer sees two ways to solve the problem of sharing state and capabilities of parent components with child components.

Composition is the suggested best practice for building complex UI classes.

The way that props can be accessed in child components allow multiple components to be pieced together, giving some components the job of handling state and the others the job of rendering the UI.

By utilizing composition, we gain several advantages. One is that UI’s sometimes have dynamic elements, passing a function as a prop from a parent to a child allows the developer to compose multiple possible UI from the a set number of components.

Another good advantage of composition is how you think about the program as a whole and each of its component elements.  You can break apart a design into a series of parent and child component hierarchies and handle each individually.  Then, if you contain your styles via the component folder structure or CSS Modules, you can have a fully self contained UI element that you can pass around your project as a module.

With inheritance, the child element is tied to the parent, and can ‘inherit’ methods and properties.  With Javascript, we don’t have classical inheritance like you find in Java, or C++; rather we have prototypal inheritance.  In classical inheritance, using the ‘new’ keyword to create a new object based on a parent class, the parent class makes a copy into the the new object.  With prototypal inheritance, we don’t make a copy, but rather we set up a lineage for delegation.  I go into more detail on this in another journal post, The Not-So-Classical Javascript Form of Inheritance.

With Composition, we have no link to an obligatory parent and so the process of building modularly is far more robust.  You could still use inheritance within your components.  State and props are similar* to inheritance in that you can pass methods and properties explicitly through provided props from parent to child.


%d bloggers like this: