# React part II

### Composition

React works best with composition as opposed to inheritance. This means we create components based on other components to avoid duplication.&#x20;

Read more or about composition here: <https://reactjs.org/docs/composition-vs-inheritance.html>

{% hint style="info" %}
Javascript uses prototypal inheritance *under the hood*. Each object has a prototype from which it is instantiated by cloning. In contrast, in classical inheritance an object is instantiated based on a *class* (a blueprint).&#x20;
{% endhint %}

### Function-components

Since the introduction of **hooks** the recommended way (at least in my perception) is to write components using function-components *whenever possible*.

Read about hooks here: <https://reactjs.org/docs/hooks-intro.html>

{% hint style="info" %}
Class-components are fine to use and will not be deprecated. We simply prefer the functional components.
{% endhint %}

### Side-effects and pureness

A side-effect happens when we change the outside world. This can be fetching data from an API, logging data to the console-log, mutating a variable.&#x20;

A function without side-effects is called a pure function. Pure because it does not modify the world around it.\
\
Example:

```javascript
// Pure-function
const add = (a, b) => a + b;

// Impure-function

const randomNum = num => num + Math.random();

// Another impure-function

let num = 10;

const addFive = () => num += 5;
addFive()
num // 15
```

The function add takes two numbers and returns the sum of both. It always does the same thing. However, the function randomNum is impure. It returns a different number on every call. Aside from a coincidence we get a different number back every time we call the function.

The last function is also impure. We add 5 to the outside variable called **num**.&#x20;

{% hint style="info" %}
Always keep your functions pure whenever possible. As a bonus: they are easier to test.
{% endhint %}
