React Hooks : Lifecycle Methods


Here we discuss how to replicate the lifecycle methods of a class component in a functional component using react hooks.


For the react class lifecycle methods, we can use useEffect hook as a combination of componentDidMount , componentDidUpdate and componentWillUnmount.

States and lifecycle methods are the important features of a class- based components. As referred in useState Hook , useState helps us to bring states to functional components. Like useState, useEffect allow us to handle lifecycle methods.

From the name itself it is well understood about the usage. useEffect hook, will be invoked every time when something effects the component.

  • componentDidMount

We replicate componentDidMount with 
useEffect( fn , [ ]). Here this useEffect hook will be invoked only when the component is mounted. Also the ( [ ] ) as the second argument reminds the useEffect hook that, it needs to be executed once when the component gets mounted.



  • componentDidUpdate

We replicate componentDidUpdate with useEffect( fn ). The optional parameter ( [ ] ) is skipped. ie, this hook will be evaluated on every re-render of the component. 





Also to conditionally execute based on prop value change, then the usage should be useEffect ( fn , [ prop value ] ).
Here useEffect will execute only when the value of prop changes.



  • componentWillUnmount

We replicate componentWillUnmount with
useEffect( fn with return statement , [ ] ). There should be a return statement inside the useEffect function. ie if a  useEffect hook returns a function, then that function is invoked only when the component is removed.




            Umesha Sree Veni UB


Comments