React Hooks Equivalent:
constructor(props): You no longer need a constructor to initialize state in function components. Instead, you use the useState
Hook.
render(): This is the same as the return statement in the function component.
componentDidMount(): Replaced by the useEffect
Hook with an empty dependency array. This ensures that the effect runs only once after the initial render, similar to componentDidMount
.
useEffect(() => {
// Code here runs once after the component is mounted
}, []);
React Hooks Equivalent:
render(): Again, this corresponds to the return statement of the function component.
componentDidUpdate(prevProps, prevState): This is replaced by the useEffect
Hook without an empty dependency array, where you can specify which props or state variables should trigger the effect.
useEffect(() => {
// Code here runs after every render
});
If you want the effect to run only when specific props or state variables change:
useEffect(() => {
// Code here runs when specificProp or specificState changes
}, [specificProp, specificState]);
React Hooks Equivalent:
componentWillUnmount(): The useEffect
Hook can also handle cleanup by returning a function inside the effect. This function will be called when the component is unmounted.
useEffect(() => {
return () => {
// Cleanup code here runs before the component unmounts
};
}, []);