Component Lifecycle
Lifecycle refers to the different stages of a components life, from creation to clean-up and each of the stages in between, such as attachment/mounting, rendering and updating. This means we think of our components as something that will have multiple events during its existence. To help us manage this lifecycle there are a few aspects of our component's life we need to be aware of:
rendering
: when the component function is called and the HTML is drawn in the DOM. Can happen multiple times during the component's life.mounting
: the first time our component renders.unmounting
: when the component is removed from the DOM.updating
: when something in our component changes (i.e. the value of a prop or state).
When a component updates, react will re-render our component. If the returned HTML differs from the HTML present in the DOM, it will update the DOM to reflect this.
useEffect
To tie into this cycle, and do things at certain stages of the components life, we use the React hook useEffect
. After the component updates and (re-)renders, effects will be executed. We can provide the useEffect
hook a "dependency array" of values to keep track of and use to control when the effect will execute.
If we provide it no array, useEffect will call our function after every update:
useEffect(() => {// code to be executed after EVERY update})
If we provide it an array of values (variables), useEffect will call our function after one of those values changes:
useEffect(() => {// code to be executed after myVar changes}, [myVar])
If we provide it an array but no values, useEffect will call our function only after our component mounts:
useEffect(() => {// code to be executed after mount}, [])
For a deeper look into useEffect, here's a basic flow chart and the containing article: Guide to useEffect.
Also, be sure to have a look at the Hooks Overview and the Effect Hook pages in the React documentation.