TL;DR: Full credit to this Stack Overflow answer:
For the stable version of hooks (React Version 16.8.0+)
For componentDidMount
useEffect(() => {
// Your code here
}, []);
For componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
For componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
So…
While working on my side project, of which I wrote in my series The Lean Startup hands on, I came across a new challenge. I wanted to reload the content of a functional component when its props changed.
It is great when a side project brings you opportunities to learn new things. In this case I needed to learn how to implement what I would normally do via a Lifecycle Event in a React Class Component, but using React Hooks in a Functional Component.
As my usual way of looking for answers, I first turned to Stack Overflow. A quick search, linked above, gave me all I needed to know and more. How to implement basic lifecycle events using the useEffect
hook. So here they are.
componentDidMount
useEffect(() => {
// Your mount code here
}, []);
componentDidUpdate
useEffect(() => {
// Your update code here
}, [yourDependency]);
componentWillUnmount
useEffect(() => {
// Your mount code here
return () => {
// Your unmount code here
}
}, []);
Top comments (0)