Ways to mimic lifecycle methods using useEffect hook
We know that the useEffect() is used for causing side effects in functional components and it is also capable of handling componentDidMount(), componentDidUpdate(), and componentWillUnmount() life-cycle methods of class-based components into the functional components.
useEffect(()=>{
//You can add your code here for mounting phase of component
console.log("Mounting in Functional Component")
},[])
// adding an empty array ensures that the useEffect is only triggered once
// (when the component mounts)
useEffect(()=>{
//You can add your code for updating phase of component
console.log("Updating in Functional Component")
},[values])
//values triggers re render whenever they are updated in your program,
//you can add multiple values by separating them by commas
useEffect(()=>{
return()=>{
//You can add your code for unmounting phase of component
console.log("Functional Component Removed ")
}
},[])
//Write all the code of unmounting phase only inside the callback function
ReactJS useEffect Hook
React useEffect hook handles the effects of the dependency array. The useEffect
Hook allows us to perform side effects on the components. fetching data, directly updating the DOM and timers are some side effects. It is called every time any state if the dependency array is modified or updated.
Table of Content
- What is useEffect hook in React?
- Why choose useEffect hook?
- How does it work?
- Importing useEffect hook
- Structure of useEffect hook
- Controlling side effects in useEffect
- Ways to mimic lifecycle methods using useEffect hook