Welcome to an introduction to React Lifecycle Methods! This guide aims to help us learn a few things:
- What is the React Lifecycle?
- Why do we use React Lifecycle Methods?
- What are some React Lifecycle Methods?
- Vocabulary: "mounting", "unmounting", "JSX"
Now that we know what we will learn, let's get started.
You can think of the React Lifecycle as the life of a component. Each component experiences a lifecycle through mounting, updating, and unmounting. Colloquially, the birth, the growth, and the death of a component.
Mounting establishes components into actual DOM elements that will be displayed in the DOM, and thus, to the client-side.
Unmounting, as we can imagine, is the process of removing DOM elements from the DOM.
In a previous post, I explained what React is and what React Components are. To summarize, React uses a component-architecture to make building user interfaces more efficient. As components allow an application to implement a separation of concerns, or the single responsibility principle, there are a lot of moving parts(ahem, components) to a React-built application.
Therefore, components need to only "live" on the client-side when necessary. Hence, a lifecycle!
We only want users to see a component's rendered output when it makes sense because we want our application experience to be succinct and easy.
For example, a component called "SignupForm" may only be mounted when the signup link is clicked and may be unmounted as the user is redirected to the application home page after successful a signup.
- is the most used lifecycle method, as it is required in every React class component.
- is a pure function; render() has no side effects => it will always returns same output given the same input.
- is in charge of rendering your component to the UI.
- returns JSX.
- cannot modify component state as its principal purpose is to render the component to the client.
- is called before a component is mounted.
- is used for initializing local state.
- assigns an object to "this.state" through super(props).
- is no longer necessary for class components through ES6.
- can be replaced with creating an object using "this.state".
- gets invoked after a React component has been mounted.
- supplies a place for API calls and fetching remote data.
- allows you to use setState() to update state.
- gets invoked just before the component unmounts.
- represents the end of a component's lifecycle.
- implements "clean up", such as clearing a timer, clearing a cached store.
- Mounting: placing a component into the DOM.
- Unmounting: removing a component from the DOM.
- setState(): when called, tells React that the state has changed.
- Single responsibility: assigning individual responsibility to individual pieces, such as components.
- pure function: a function that returns the same output given the same input; has no side effects.
🪐 Thank you for reading along.
🪐 Comment below to continue the discussion!