Coding React components: Single Level of Abstraction
Learn how to make your React components easier to understand by following the Single Level of Abstraction principle.
The Single Level of Abstraction (SLA) principle tells us that:
Each method should be written in terms of a single level of abstraction.
What “writing in terms of a single level of abstraction” means is, well, quite abstract 😅. I think it is best understood using an example.
Take this function to place an order in an e-commerce application.
We are mixing many levels of abstraction there. On the one hand, we are hiding away the complexity of checking for the items availability, sending an invoice and shipping the order. On the other hand, the calculations and process of paying the order are done in place.
The SLA principle tells us to refactor that code into different functions, each one dealing with the same level of abstraction:
Now every line in placeOrder
is at the same level of abstraction. The function reads smoothly, and you get into the details of paying an order as you go down the chain of function calls.
SLA in React components
The SLA principle can be applied to React components, specially to the JSX code in the render method.
In the next code snippet we define a ColorPicker
component:
The render
method mixes two different levels of abstraction. The color model selector is a raw, basic HTML component, while the actual implementation of the color sliders is hidden away. You can try to mentally “read” the render
method:
So, this component renders a select field…it has three different options, RGB, CMYK and HSB. Oh, the selected option will be stored as the color model. And then it also renders some color sliders for the given color and model.
The SLA principle tells you to keep abstractions to the same level. You’ll have to extract the choice selector to it’s own component:
Now you can use this new component in your ColorPicker
implementation:
If you “read” the render
method again, you’ll notice the change:
This component renders a color model selector and some color sliders for the given color and model.
The next time you write a React component, try to think about the different levels of abstraction involved, and apply the SLA principle. The result will be much more easier to read, understand and maintain.