UseEffect Hook React:
useEffect - Hook, Which can be used in Functional Component.
- We can do API calls
- We can Update State here
- We have dependency Array
- Empty [] => Called only once when component is loaded
- [props / state] => Called everytime when prop /state changes
The useEffect hook will replace method of Class Component
-componentDidMount --> []
-componentDidUpdate --> [props/state]
-componentWillUnmount --> return ()=>{ //cleanup }
// React Importing useEffect
import React, { useEffect } from "React";
// HOOK CALLED HERE
useEffect(() => {
// code
// effect
// API call
// logic
// return will be called only when components UNMOUNT
return () => {
// Cleanup timer etc.
};
}, []);
useEffect(() => {
let timerId = setTimeout(() => {
// perform an action like state update
timerId = null;
}, 5000);
// clear the timer when component unmouts
return () => clearTimeout(timerId);
}, []);
Top comments (0)