By Gene Lorenz Sarmiento
Last Edited: February 4, 2021 8:10 pm GMT+08:00
I made this article about useEffect via Scrimba’s free React lesson (https://scrimba.com/learn/learnreact).
First, what is a side effect in React. A side effect is an effect that React can’t handle on its own:
Credits to [Scrimba](<https://scrimba.com>)
If you are familiar with class-based components, you can think of the useEffect() as the componentDidMount
, componentDidUpdate
, and componentWillUnmount
to control side effects. In functional components, you can use hooks(which is like Class-lifecycle methods in React). One of the hooks is called useEffect()
The Effect Hook lets you perform side effects in functional components
UseEffect will run when every component is rendered
2 parameters (1 is a callback function and 1 optional (This can be required) )
const [count, setCount] = React.useState(0);
// side effects
React.useEffect(function() {
console.log("Effect ran")
}, [count])
// 1st param - Callback function
// 2nd param - dependencies array
// First parameter run when the 2nd parameter changed/re-rendered
/* if the second parameter is an empty array [],
it will not render every time that any state has change
*/
// useEffect() depends on the 2nd parameter if it should run
To clean up the side effects, you should return the value of it.
React.useEffect(() => {
function watchWidth() {
setWindowWidth(window.innerWidth)
}
/* can cause a memory leak (if the component was removed on the DOM)
* if not removed on return */
window.addEventListener("resize", watchWidth)
return function() {
window.removeEventListener("resize", watchWidth)
}
}, [])