TG
Miscellaneous·2 min read

Basics of Component Composition

Fundação Bradesco course, free online course

Ler em português
Basics of Component Composition

In JavaScript there is the concept of pure functions, which comes from the functional programming paradigm. The idea is that a function must return the same result when called more than once with the same parameters. It doesn't depend on anything beyond the parameters it receives and doesn't perform any external modification.

Examples of pure functions:

const sum = (a, b) => a + b;
const multiply = (a, b) => a * b;
const subtract = (a, b) => a-b;

You can call:

sum(2,3); // the result will always be 5

Example of an impure function:

giveMeANumber = (a, b) => Math.random(a+b); // the result will be random

It has an external modification from another external piece of code, Math, which is the object with static methods.

You can even pass the same parameters every time, but the result will always be different:

giveMeANumber(1,3); // 0.7790099266309651
giveMeANumber(1,3); // 0.6637543698896975
giveMeANumber(1,3); // 0.7493726954950461

The idea behind component composition is being able to build more generic components (pure functions, single responsibility) so that other components can use them.

Button example: button.js

Here I create just a simple button that receives a children and a function that is executed when the user clicks the button.

Now I create two other components that make use of this Button via composition.

We create the file likeButton.js:

We create another file deslikeButton.js;

I'm simply creating a composition, where LikeButton returns a Button passing the parameters I want: the definition of the anonymous function that shows an Alert and the text with the button's name.

And now let's use it in App.js:

Notice how the logic stays hidden inside Like and Deslike Buttons and also inside the Button itself. So App.js ended up with components composed of another component, each with its own single, separate responsibility.

This is a basic example, but it gives you an idea of the power of this methodology.

I believe later on I'll post another more advanced example, as I learn more about these concepts within JS and React.

Credits: React Ninja course by @fdaciuk

Thiago Marinho

February 4, 2018 · Brazil