Mimicking lifecycle methods using useEffect hook
useEffect hook
The useEffect hook is used to perform side-effects based on certain conditions. It takes in two arguments, a callback function and an array of dependencies. The callback function is executed after the component is mounted and whenever one or more of the dependencies change. The dependencies array is optional and is used to specify the values that the callback function depends on.
useEffect(() => {
// code to be executed whenever component re-renders
})
If we don't pass the dependencies array, the code inside the useEffect will be executed everytime the component re-renders.
Mimicking componentDidMount
useEffect(() => {
// code to be executed after component mount
}, [])
The empty array tells React that the effect should run only once, after the component has mounted. This is equivalent to componentDidMount.
Mimicking componentDidUpdate
const [state, setState] = useState('');
useEffect(() => {
// code to be executed after component updates
}, [state]);
In this case, the code inside useEffect runs only when the value in the dependencies array change.
Mimicking componentWillUnmount
useEffect(() => {
// code to be executed after component mount
return () => {
// code to be executed just before component unmounts
}
}, [])
The callback function passed to the useEffect hook is executed after the component mounts and returns the cleanup function. This cleanup function will be executed just before the component unmounts.