State Life Cycle In React

State Life Cycle In React

introduction

  1. The different stages that an instance of a component goes through. There are 3 primary stages to the react lifecycle.

    • Mounting

    • Updating

    • Unmounting

  2. Mounting: It is when the component is rendered for the first time

  3. Updating: The component re-renders when the state/prop value of the component changes

  4. Unmount: The component is removed from the dom This is the final stage and a component cannot be updated once it is unmounted. However a new instance of the component can be still Mounted

UseEffect Hook

  1. A React hook for performing side effects around the component lifecycle. The useEffect hook takes in a callback function and an optional dependency array.If no dependency array is provided, the callbackmount. function will run on every render. If there is a dependency array provided, the callback function will only run on If no dependency array is provided, the callback function will run on every render. If there is a dependency array provided, the callback function will only run on

  2. The callback function can also return a cleanup function, which will run on unmount and before the main effect function runs on any re-renders. For example:

     useEffect(() => {    // Update the document title using the browser API//
     document.title = `You clicked ${count} times`;  },[]);
    
  3. One thing to make sure of while use effect is that we should not create infinite loops

  4. Infinite loops are created when we update the state inside the use effect hook and the same state is passed into the dependency array