The Effect Hook let’s you perform side effects in function components.
Let’s explore useEfect in React on therr lifecycle phases of React component.
- Mount
- Update
- Unmount
1. useEffect Hook (Mount)
useEffect hook with empty dependency array work as componentDidMount andruns just on the mount.
import React from 'react' ;
const UsseEffectHookMount = () => {
useEffect(() =>> {
console.log("useEffect runs on mount");
},[]);
return(
<h2>Hello</h2>
);
}
export default UseEffectHookMount;
2. useEffect Hook (Update)
useEffect hook with dependency array works as componentDidUpdate and run every time the array value changes.
import React from 'react' ;
const UsseEffectHookMount = () => {
const [count, setCount] = useState(0)
useEffect(() =>> {
console.log("count changed");
},[count]);
return(
<button
onClick={() => {
setCount(c => c + 1);
}}
>
{count}
</button>
);
}
export default UseEffectHookMount;
3. useEffect Hook (Unmount)
You can execute componentWillUnmount behaviour by returning a function inside useEffect. Here, you can perfom clean up task that you perform in componentWillUnmount.
import React from 'react' ;
const UsseEffectHookMount = () => {
useEffect(() => {
return () => {
console.log("Component is unmounting");
};
},[]);
return(
<h2>ComponentWillUnmount</h2>
);
}
export default UseEffectHookMount;





Leave a comment