Common class lifecycle methods
1// happens as soon as your component is mounted2componentDidMount() {}3
4// happens as soon as the updating begin5componentDidUpdate(prevProps, prevState, snapshot) {}6
7// for certain performance optimizations8shouldComponentUpdate(nextProps, nextState) {}9
10// happens just before the component unmounts11componentWillUnmount() {}12}How can we map those lifecycle hooks to useEffect?
Here are basic templates to convert a class lifecycle method to a useEffect hook:
componentDidMount
Create an empty dependency array and pass it to the useEffect hook.
1useEffect(() => {2 // code to run when the component is mounted 3
4 // Make sure this is empty to ensure the hook will only run once5}, [])shouldComponentUpdate
Add the dependency array and pass it to the useEffect hook.
1// props: {name}2// state: {visible}3
4useEffect(() => {5 // ... code to run6
7 // the dependency array below is "equivalent" to:8 // the effect will trigger if9 // props.name !== nextProps.name || state.enabled !== nextState.enabled10}, [name, visible])componentWillUnmount
A useEffect can return a function whose body will be executed when the component is unmounted.
1useEffect(() => {2 return () => {3 // code to run when the component is unmounted4 }5}, /* with or without dependency array */)componentDidUpdate
This is a bit subjective because it's up to the developer to decide how componentDidUpdate should behave (the simplest is the same as componentDidMount mapping).
It could also be a combination of componentDidMount and shouldComponentUpdate mapping with the addition of a reference variable to check if the component has been mounted as shown below:
1const hasMount = useRef(false)2
3useEffect(() => {4 if (hasMount.current) {5 // code to run when the component is updated6 } else {7 hasMount.current = true8 }9}, /* dependencies */)`Additional Note
- You can only define one of each lifecycle method in a
classcomponent. When using hooks, you can define as manyuseEffectas you want. - You can only use
useEffectin afunctioncomponent
Conclusion
The examples above are simple ways to map a class lifecycle hooks component to a React hooks, and there are many other ways to do it. The good news is that you don't need to think of mapping lifecycle hooks to useEffect since React hooks introduced a different paradigm on how we can create a React component and how we can manage side-effects. This mapping is only useful when I'm refactoring a class component to be a function component. For newer projects, I ought to think that the class component does not exist.
