Learn The useEffect Hook in React
5 June, 2022
17
17
0
Contributors
The useEffect hook allows you to perform side effects in function components.
Some examples of side effects are fetching data, directly updating the DOM, timers, etc.
It’s similar to componentDidMount and componentDidUpdate.
By using this hook, you tell React that your component needs to do something after render. React will remember the function you passed(let’s call it our effect), and call it after performing the DOM updates.
By default, it runs both after the first render and after every update.
It’s always placed inside a component, i.e it can’t be used outside the App()
. It allows us access to the count state variable (or any props) right from the effect.
Syntax
useEffect accepts two arguments, the second argument is optional
Examples:
Using the timer function example above, we notice it keeps counting even though it should only count once!
useEffect
runs on every render. That means that when the count changes, a render happens, which then triggers another effect.
We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect
in this array.
Example
Another Example
Here is an example of the useEffect
Hook that is dependent on a variable. If the count
variable updates(chnages), then the effect will run again:
useEffect with the cleanup
Using the timer function.
!{clean up](https://res.cloudinary.com/d-a-r-k-c-o-d-e/image/upload/v1654424072/work/React%20Hooks/useEffect/clean_up_r2ezlu.gif)
What you should not add as a dependency.
- No need to add state updating functions such as setValue. setValue function is never going to change even if the component re-renders.
- No need to add built-in functions like fetch as these will also never change.
- Very Important Never add the states as dependencies that are being changed in the effect function. Otherwise, it will cause an infinite loop.