- Perform side effects in your components
- Fetching data, directly updating the DOM, and timers.
Syntax : useEffect(<function>, <dependency>)
1.No dependency passed - Runs on every render:
useEffect(() => {
//Runs on every render
});
Output Times Increase automatically :2.Empty Array in dependency - Runs only on the first render:
useEffect(() => {
//Runs only on the first render
}, []);
After adding Empty Array in Dependency
Output :
3. Props or state values - Runs on the first render And any time any dependency value changes
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
Adding State dependency in the Array :
Output :
4. Effect Cleanup - Some effects require cleanup to reduce memory leaks
UseEffect(() =>{let timer = setTimeout(() => {}); return () => clearTimeout(timer)},[])
After adding cleanup : first time its rendered , once then it have been cleaned up
Output:
No comments:
Post a Comment