useEffect Hook
Learn how the “useEffect” hook replaces traditional lifecycle methods in React. This lesson will go through its use case, syntax, and usage. Later in the chapter, practice exercises are provided.
We'll cover the following
What is it?
The useEffect
hook provides a way to manage side effects in a React functional component. Think of the useEffect
hook as a partial replacement for React lifecycle events. With the useEffect
hook, it is possible to replicate behavior for componentDidMount
, componentDidUpdate
and componentWillUnmount
methods.
In other words, you can react upon changes happening in a component that is using the useEffect
hook. How great is that 🎉?
When do we use it?
Some common scenarios to use the useEffect
hook with are mentioned below:
- Add an event listener for a button
- Fetch data from API when component mounts
- Perform an action when state or props change
- Clean up event listeners when the component unmounts
In short, the above-mentioned lifecycle methods can be replaced with the useEffect
hook.
Syntax
useEffect
hook takes the two arguments mentioned below:
- It accepts the first argument as a callback function. By default, this function will run after every render but this depends upon the value of the second argument.
- The second argument is an optional dependencies array.
useEffect
hook checks this array to compare the previous and current value for those dependencies and then it runs the callback function but only if one of the dependencies has changed.
useEffect(() => {
// some code
}, [someProp, someState]);
The role of dependencies array will be explored in great detail in the next chapter called Advanced: Deep Dive into useEffect Hook. For the purpose of this lesson, an empty array for dependencies will be used.
Get hands-on with 1200+ tech skills courses.