What's useEffect for ?
useEffect is a hook you'll need if you want to handle side effects in a functional component.
Side effects are code running after React has updated the DOM.
An example please ?!
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
const [style, setStyle] = useState("#A5CE86");
const change = () => {
setCount(count + 1);
}
const color = "#F98E72";
useEffect(() => {
setTimeout(() => {
setStyle(color);
}, 2000);
}, [color]);
return (
<div>
<h1 style={{ color: `${style}` }}>{count}</h1>
<button onClick={change}>Change!</button>
</div>
);
}
Ok... what do we have here ?
This code shows a counter. Each time you click on the button, the count
will increase by 1. And there's a little color changing side effect...
1.The component is shown to me for the first time:
2.After the DOM is rendered, my component run the side effect... :
useEffect(() => {
setTimeout(() => {
setStyle(color);
}, 2000);
}, [color]);
3.... and change the value of my style
state:
4.I click on the button:
<button onClick={change}>Change!</button>
5.It increases my state count
by +1
:
const change = () => {
setCount(count + 1);
}
7.After the DOM is updated, my component does't run the side effect because I told him to run it only if color
changed, by adding a dependencies to useEffect:
useEffect(() => {
setTimeout(() => {
setStyle(color);
}, 2000);
}, [color]); //my dependency
You can add a console.log into the setTimeout()
method and run the code. You will see that React run the side effect only one time thanks to the dependency. Now try to remove it, and you will see the side effect is running every time my component is updated.
What now ?
It was a glance at useEffect. To dive deeper into this concept have a look at:
Hope you enjoyed this post and will close this window with a better understanding of useEffect.
✌️
Top comments (0)