Lesson 2. Trigger side effects with useEffect 1. Meet useEffect
Let’s start with an example. We want to create a component that receives a
title prop, and logs this prop in the console each time it is updated.
Result
Let’s focus on the call to useEffect:
useEffect(() => {console.log('New title:', title)}, [title])
As you can see, useEffect accepts two parameters:
- a function, and
- an array of the values that, when updated, should trigger the function’s execution.
The array passed as second parameter is called the dependencies array. In our
example, it contains one value, title, meaning that each time title is
modified, the function will be executed: we’ll log title’s value in the
console.
Note that the component’s first mount triggers the function execution too. This means that by passing an empty dependencies array, we can trigger an effect when the component is mounted:
useEffect(() => {console.log('I’m mounted!')}, [])
Logging a message right away in the console is not very fun; what if we want to wait a couple of seconds before logging it?