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.
Read more or about composition here: https://reactjs.org/docs/composition-vs-inheritance.html
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
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.
A function without side-effects is called a pure function. Pure because it does not modify the world around it. Example:
// 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.
Last updated
Was this helpful?