Welcome back!
This is the second blog in the React Hook series, where we're learning about different hooks used in React, and our today's hook is the useEffect
hook. Before we get started, I'd recommend reading the last blog of this series useState Hook. Though this hook is completely independent of the useState
hook, and you can read and learn from it without any prior knowledge of hooks, it would beneficial to have some basic understanding of the hooks.
What is the use of useEffect hook in React?
The useEffect
hook is used in our components to perform side effects. Side effects are the task that happens outside the normal component evaluation. Data fetching, web API, and manually changing the DOM are some examples of side effects.
How to use the useEffect hook
- Import useEffect hook
It can be imported by destructuring from the React library using the following code:
import {useEffect} from "react"
- Syntax of useEffect hook
useEffect ( <function> , [dependency] )
There are two arguments:
(i) The first is a function that will be invoked on every render until the dependence
is provided.
(ii) The second argument is the dependence
which will enable useEffect
to call our specified function if it changes.
- Why use dependency
As previously stated, the useEffect
hook will call our function on every render, resulting in an infinite loop and crashing the browser. However, there are ways to avoid it by providing dependency.
1) Providing an empty array [] as a dependency
useEffect( () =>{
// it will run only on the first render
},[]}
2) Providing the props or state as the dependencies
useEffect( () =>{
// it will run on the first render
// it will also run every time the given dependencies changes
},[ props , state ]}
Check out the file NonEmptyDependency.js
, and EmptyDependency.js
. and console of the following codesandbox to better understand the examples.
Cleanup function in useEffect
Consider the following scenario: we obtain a fetch of a specific user via the user's id, but before the fetch is completed, we change our minds and attempt to obtain another user. While the previous retrieve request is still in progress, the prop, or in this example, the id, updates.
To avoid exposing our application to a memory leak, we must then cancel the fetch using the cleanup function.
Every time the useEffect
is called the cleanup function will also run except on the first render.
Let us clean the Timeout function at the end of the useEffect
hook in the following codesandbox.
That's all for this blog. Continue reading this React hook series to learn more about React hooks. In the next blog, we'll look at the 'useContext' hook, which is used to handle state management in React globally.
Feel free to leave your valuable feedback in the comments below.
To learn more about React, JavaScript, and Web development, follow me on Twitter.
Reference: W3Schools, Blog
Top comments (0)