React Mapping React Life Cycles into UseEffect()
2 min readNov 16, 2021
How to convert Life Cycles methods into useEffect hook?
In this article, I’ll show you how to map react life cycles to useEffect hook.
React Class components Life cycles List
1) componentDidMount() {}
2) componentDidUpdate(prevProps, prevState, snapshot) {}
3) shouldComponentUpdate(nextProps, nextState) {}
4) componentWillUnmount() {}
1- ComponentDidMount
Pass an empty dependency Array
useEffect(() => {
// code run when the component is mounted
// Make sure this is empty to ensure hook will only run once
}, [])
2- shouldComponentUpdate
Add any value to the dependency array of useEffect
/ props: {name}
// state: {visible}
useEffect(() => {
// ... code to run
}, [name, visible])
3- componentWillUnmount
we can use this useEffect with and without Dependency Array
useEffect(() => {
return () => {
// code to run when the component is unmounted
}
})
4- componentDidUpdate
const hasMount = useRef(false)
useEffect(() => {
if (hasMount.current) {
// code to run when the component is updated
} else {
hasMount.current = true
}
}, /* dependencies */)`
Important Points
- You can only define one of each lifecycle method in a
class
component. When using hooks you can define as manyuseEffect
as you want. - You can only use
useEffect
in afunction
component
Follow me on LinkedIn to catch more interesting Javascript and React Js concepts
Link: https://www.linkedin.com/in/azeem-aleem-560345148/
Thanks for reading this article
Regards
Azeem Aleem