React Component Lifecycle

The Component Lifecycle (before React 16.18)

These are the component Lifecycle hooks: A way to do hook into the various stages of the component: where we can set up data the component can use, where we will do things like making HTTP requests for external data, and where we will tear things down in the HTML when the component is remote.

Important: Do not confuse “Lifecycle hook” (which is an older way of using class-based components with “React Hooks” — which is a newer, all-functional way of writing components. In the newer paradigm, you can replicate some of this functionality, but you do not have access to the true Lifecycle hook.

Unfortunately, the two names are very close to each other, leading to a natural confusion for people learning about react. So the key takeaway is 1) “Lifecycle hooks” do not refer to “React hooks”— they mean quite the opposite things in fact, and 2) Although you can so some of what you need with the Context API using Functional components, if you need the full range of Lifecycle hooks, you will still need to use Class-based components.

constructor(props)

  • You must call super(props) inside of your constructor
  • Do use this to set up state in your component initially.
  • Don’t cause side effects (like loading an http request)

This lifecycle hook used to be used to setup astate.

getDeriviedStateFromProps(props, state)

Executes before the render method.

  • If you have props that change you can sync your state to them ( rare
  • Used for when props that change causes an internal state change
  • Don’t cause side-effects: https requests, timeouts, etc

render()

• Prepare the JSX, render the output

Render The Children Components (Each)

componentDidMount()

  • DO Cause side effects
  • Cause an async operation to defer to a  .then block that will change data & state
  • Update state  synchronously
  • Don’t call setState synchronously