An Interest In:
Web News this Week
- April 29, 2024
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
'useEffect' in depth
What is useEffect for?
useEffect was introduced in react 16.8, before this was released react developers would use componentDidMount and componentWillUnmount.
The useEffect hook is a built-in React hook that allows you to run side effects in functional components. This side effects are actions that do not directly affect the UI but it can include things like fetching data, adding event listeners, etc.
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.
First Example
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.
Second Example
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.
Cleanup in useEffect?
This is something not always is being used or even taught, but is indeed really important for time efficient and memory leaks.
We should run cleanup in useEffect to we avoid having memory leaks in our application which can cause our app to be slower.
Example with cleanup
import React, { useState, useEffect } from 'react';function Timer() { const [time, setTime] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setTime(prevTime => prevTime + 1); }, 1000); return () => { clearInterval(intervalId); }; }, [time]); return <div>{time} seconds have passed.</div>;}
In the example above we can see that i added a return which will return a clearInterval that will do a cleanup with the intervalId and we will avoid memory leaks in our application.
Hope someone found this useFul and if you have any questions and would be happy to answer them.
Lautaro.
Original Link: https://dev.to/lausuarez02/useeffect-in-depth-30hp
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To