Before Hooks, function components were only used to accept data in the form of props and return some JSX to be rendered. However, as we learned in the last lesson, the State Hook allows us to manage dynamic data, in the form of component state, within our function components.
- fetching data from a backend service
- subscribing to a stream of data
- managing timers and intervals
- reading from and making changes to the DOM
Why after each render?
Most interesting components will re-render multiple times throughout their lifetime and these key moments present the perfect opportunity to execute these “side effects”.
There are three key moments when the Effect Hook can be utilized:
- When the component is first added, or mounted, to the DOM and renders
- When the state or props change, causing the component to re-render
- When the component is removed, or unmounted, from the DOM.
Later on in this lesson, we’ll learn how to further fine-tune exactly when this code executes.
In the editor, we’ve defined a component as both a class and a function, each with the same “side effects”.
Even if you are unfamiliar with class component lifecycle methods, start by having a look at both implementations, just to get a sense of both options.
Note: Understanding lifecycle methods in class components is not a pre-requisite for this lesson.
In the class component in PageTitleClass.js, the logic for setting the document title is split between two functions –
Compare this to the function component in PageTitleFunction.js, where the logic is written in one place –
Both component implementations have the same behavior, but reading and maintaining the function component will be easier.
Ready to start using the Effect Hook? Great! We’ll dive into the details of how to use this Hook throughout this lesson!