What is useEffect
What:
The useEffect hook is a built-in React hook that allows you to run side effects in functional Components.
The side effects are actions that do not directly affect the UI but it can include things like fetching data, adding event listeners, etc.
When:
- You need to run code after render.
- You want to re-run code (on update).
- You want to clean up resources.
Why:
replaces lifecycle methods like ComponentDidUpdate and ComponentWillUnmount from class Components.
Keeps functional components clean and avoids duplication of logic.
Why useEffect accept two arguments?
It takes two arguments, the first argument being a function that contains the code for the side effect you want to perform and the second argument which is optional being how many times we want it to be perform.
Eg:
import React, { useState, useEffect } from 'react';
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setTime(prevTime => prevTime + 1);
}, 1000);
}, []);
return <div>{time} seconds have passed.</div>;
}
In the example above it will run just once after the component in mounted
Eg:
import React, { useState, useEffect } from 'react';
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setTime(prevTime => prevTime + 1);
}, 1000);
}, [time]);
return <div>{time} seconds have passed.</div>;
}
In the example above we can see how i passed the second argument so it just renders every time 'time' changes.
Top comments (0)