# React Lifecycle Methods

Every component in react goes through a series of lifecycle events very similar to that of human lifecycle: cycle of birth, growth and death.</br>
In react we call them :</br>
Mounting: Birth of the component</br>
Updating: Growth of the component</br>
Unmounting: Death of the component</br>

Lifecycle methods:


1. `render()`
  - As the name suggests if you want to render elements in the DOM,  we could use the `render()`  method.</br>
  - `render()` mounts the component onto the DOM and renders them to the UI. </br>
  - `render()` is invoked whenever there is a variation in the component’s state `(this.state)` or props`(this.props)`.</br>
  - React requires `render()` to be pure i.e with no side-effects which means you cannot update component's state within render (no using setState).</br>
  - `render()` could return strings, numbers, arrays, fragments, Booleans or null value, portal, or React elements.</br>
  - `render()` will not be invoked if shouldComponentUpdate() returns false.</br>
    Examples:
    
    //return string</br>
    ` render() {return "Hello!!"}`
    
    //return null, doesnt render anything</br>
    `render() {return null}` 
    
    //return fragments </br>
    `render() {return (<React.Fragment><div>Hello</div></React.Fragment>)}`
    
    //return arrays</br>
    ` render() {return [<div key="1">Hello</div>, <div key="2">World</div>];}` 
    
    //return Components</br>
    `render() {return <div>Hello {this.props.name}</div>}`

2. `componentDidMount()`  👶

  - After the `render()` method, when the component has been inserted into the DOM, `componentDidMount()` is called.</br>
  - Here one can setup any subscriptions or send any network requests. </br>
  - Also one could update state using `setState` inside `componentDidMount()` which would further trigger a render. </br>
  - However, the problem here is that it may cause performance issues so it is advisable to this pattern with cation. Good practice includes you assigning value to the initial state.</br>
  For example:  Consider that you setState of a component initailly in the first render and   the thing to which you are going to setState is in the localStorage. </br>
  So instead of doing something like this which could again trigger a render because of setState:</br>`componentDidMount({this.setState(JSON.parse(localStorage.getItem("someData")))}`.</br>
  - You could give your state an initial value: `state=JSON.parse(localStorage.getItem("someData"))`</br>
  - This pattern is mostly used when you need to measusre a DOM node before rendering something that depends upon its size.  Example:  tooltips, modals or incases where you need to measure window dimensions</br>
  - In functional React it is similar to `React.useEffect` with an empty dependency array
  ` React.useEffect(() => { // Your code here }, [])`
    Example:
  
    %[https://codesandbox.io/s/componentdidmounnt-z3pp1w]

3.  `componentDidUpdate()` 💅

 - It runs anytime there are changes to state or props to this component<br/>
  For example:
  If you type something on the input field  (i.e. if you update the component),  `componentDidUpdate()`  runs and update is console logged into the console.<br/>
  - In functional React it is similar to `React.useEffect` with an no dependency array
 ` React.useEffect(() => { // Your code here })`
  %[https://codesandbox.io/s/componentdidupdate-3wp7fr]
  - `componentDidUpdate()` also receives `prevState` and `prevProps` as parameters and also the newly changed state or props. </br>
 - In functional React it is similar to `React.useEffect` with some dependency array
 ` React.useEffect(() => { // Your code here },[dependencies])`
  - This is very important as you could setState by wrapping a condition to check for state or prop changes from previous state which can save from an infinite loop to occur. </br>
  - If you directly use `setState` within this function, it will  trigger render and 
   `componentDidUpdate` infinitely</br>
  For example:
  Here if you comment out the check for prevState and click on the + button `componentDidUpdate()`will trigger the `setState` then the `render()` and again the `componentDidUpdate()` and so on.</br>

  %[https://codesandbox.io/s/componentdidupdate-si72nh]



4.`componentWillUnmount()`🪦

- `componentWillUnmount()` is called just before the  component is unmounted and destroyed. If there are any cleanup actions that you would need to do, like canceling network requests, invalidating timers, or cleaning up unwanted subscriptions that were created in the `componentDidMount()` method.
- In functional React it is similar to `React.useEffect` with a return function
` React.useEffect(() => { // Your code here return()=>{//cleanup  code} },[])`
- One cannot modify the state in  `componentWillUnmount()` method
- For example: Here in this code if you comment the `componentWillUnmount()` and try to toggle the windowTraker and unmount it from the screen and then resize the window, you will get an error saying <br/>
 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application<br/>
This is because the imperative mannual addeventListner is still listning for the resize event which then calls watchwidth  which tries to setState to the component that is not mounted anymore<br/>
 ```
        import React from "react";
        
        export default class App extends React.Component {
          state = {
            show: true,
            windowWidth: window.innerWidth
          };
        
          watchWidth = () => {
            this.setState({ windowWidth: window.innerWidth });
          };
        
          componentDidMount() {
            window.addEventListener("resize", this.watchWidth);
          }
        
          componentWillUnmount() {
            window.removeEventListener("resize", this.watchWidth);
          }
        
          render() {
            return (
              <div>
                <button
                  onClick={() =>
                    this.setState((prevState) => ({ show: !prevState.show }))
                  }
                >
                  Toggle WindowTracker
                </button>
                {this.state.show && <h1>Window width: {this.state.windowWidth}px</h1>}
              </div>
            );
          }
        }
        ```
These are most commonly used lifecycle methods.
There are more methods which you can find them [here](https://reactjs.org/docs/react-component.html).

Happy coding 🚀









 






