Ø The useEffect Hook allows you to perform side effect in your components.
Ø useEffect
accepts two arguments. The second argument
is optionaluseEffect(<Callback function>, <dependency>)
Ø
Whenever useEffect use without any dependency then it will execute callback function on every render whenever any state change in component.
Ø
Whenever useEffect use with empty
array then it will execute callback function only once whenever
component gets loaded.
Ø
Whenever useEffect use with dependency
then it will execute callback function whenever component gets loaded and after
that dependency changes again it will execute callback function.
import React, { useEffect, usestate } from 'react'
import './App.css'
function App() {
const
[count, setCount] = usestate(0)
const
[name, setName] = useState(“Hello”)
/*Without
dependency - Runs on every render*/
useEffect(()
=> {
setTimeout(()=>{
setCount(count
=> count+1);
},2000)
})
/*Empty
array - runs only on first render*/
/*useEffect(()
=> {
setTimeout(()=>{
setCount(count
=> count+1);
},2000)
},[])*/
/*With
dependency - runs on first render and anytime when it's dependency value changed*/
/*useEffect(()
=> {
setTimeout(()=>{
setCount(count
=> count+1);
},2000)
},[count,name])*/
return (
<>
<h1>I've rendered {count) times!</h1>
</>
)
}
O/P
Without Dependency
Empty Array []
Note:- To continue increasing the count, remove React.StrictMode from App.js, it will do an additional run time check in the development environment to make sure that your react app is safe
No comments:
Post a Comment