Skip to main content
- Class Components
- The React Lifecycle
- Composing and Sharing Non-Visual Behavior
- Testing Web Applications
- Class Components
- The React Lifecycle
- Composing and Sharing Non-Visual Behavior
- Testing Web Applications
Every component in React has what we call a lifecycle. The Lifecycle is a a part of how our components operate under the hood. Being able to demonstrate understanding of the React Component Lifecycle by knowing how to use a few of the “Methods” that are provided by it, will help you understand how and why react behaves the way it does at times.
At the end of this module, you should be able to:
- describe the three phases of the React Component Lifecycle
- properly explain what the `constructor` and `render` methods do and what their place is in the React Component Lifecycle
- use the `componentDidMount` function to set a component's state post render
Write all code knowing someone else will be working on it after you.
Review each preclass resource before class.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
A great introduction to what we have at our disposal when working with React.
The React component lifecycle is an important concept to leverage when it comes to writing React apps. For example, they are necessary in order for React apps to make API requests and then render based on the data that was received.
React is, in essence, a combination of multiple components. A component can be as simple as a single piece of user interface that represents a small portion of our application. Conceptually, a component lifecycle happens in three phases. This idea is displayed nicely in the following diagram from one of the maintainers of React “Dan Abramov”.
As you can see, the three React lifestyle phases are 1) Birth/Mounting, 2) Growth/Updating, and 3) Death/Unmounting.
This is the phase when the component is being built out from the ground up. A few things are happening here: Whatever initial data you want access to will be defined on the constructor of this phase
- Your render method is invoked.
componentDidMountgets called as well.
In the Growth/Updating phase you’re updating compnent data.
setStatecan be used to change the component’s state data, forcing a call torender.shouldComponentUpdateis a method one could use here to stop a component from calling render if necessary.
Again, self-explanatory, but the unmounting phase includes removing the component from the screen.
- Component is removed from the screen.
componentWillUnmountis called and can be used for any clean up you may need to do.
Dive into the documentation at ReactJSand look into some of the key pieces of the LifeCycle API.
The methods that we’re going to look at are:
constructorrendercomponentDidMountcomponentDidUpdatecomponentWillUnmount
Let’s also compare where each of these methods belong within the react lifecycle by taking a look at this diagram.
We will explore these in depth later on but for now, focus on warming up to the documentation and the idea that components have a lifecycle.
Read this medium article about the component lifecycle. Take notes and share what you learned in a paragraph to your Project Manager via Slack.
- React Lifecycle Methods: How and When to Use Them
An article thoroughly walks through when to use each React component lifecycle method, and why - React Interview Questions
An amazing breakdown of commonly seen react interview questions by _Tyler McGinnis_ - CS8 - React II Lifecycle Methods
Learn to properly explain what the `constructor` and `render` methods do and what their place is in the React Component Lifecycle
render() is the life blood of every react class component. We have to use it when building our UI. You can think of our render function as the ‘thing that tells react what will be mounted to the screen’. Learning about how this function works, and when it works, will help us all understand more about the React ecosystem and components in general.
You already know all about the constructor function as it pertains to classes in JavaScript. It’s not much different in React. The constructor’s purpose in React is to create components with inciting state data for the initial render. Any other props that the component receives on state can be done through the constructor function. We also used to bind all of our event handlers to the component via the constructor, and now we don’t have to because of some special ESNext syntax that allows us to use arrow functions on our class methods. The following snippet is an example of this.
eventHandler = () => this.setState({ foo: 'bar' });
We will have ample time to practice application set up with state data via the constructor, so for now, soak in these examples.
Let’s say we have some data from an external file living within our application. Let’s say, too, that we want our component to render a list of that data out to the DOM. We would need to import the external data as an array, ( we don’t care about the shape, or what type of data just that it lives on an array ) and use the constructor to set it up on state.
import React from 'react';
import { data } from './extraneousSource.js';
class MyComponent extends React.Component {
constructor() { // if I wanted to receive some props here I could pass them in through the constructor! constructor(props)...
super(); // if i receive props through the constructor I will need to pass them back through super(props);
this.state = {
arbitraryStateData: data,
}
}
}
This how we use the constructor in the mounting phase of our component’s lifecycle. Now that our data is set up on state, we can access it during our render portion of the mounting phase.
In conclusion, the constructor function on a React Class’ Component’s purpose is to serve up initial state data for when the time comes to mount up your DOM elements.
The render() method is one of the React lifecycle methods that is used to tell React, to return some piece of DOM. The React virtual DOM will then handle the steps to mount those DOM pieces.
The render() method is required for a class component, and without it, the component won’t work.
render should be a pure function, meaning it should return the same thing each time you call it. Its concern is to look at this.props and this.state and return some DOM element, a boolean, an array of DOM elements, and a couple of other things that you may want to reference or look into later.
The function is there to return what your component should render to the screen. Though many developers ignore it, Component is an important lifecycle method and should be regarded as such.
Another essential item to remember about render is that it is called not only in the Mounting Phase of the component lifecycle but also during the Updating Phase. This duality makes the render() method unique because it exists across multiple phases.
Now that we have our state data set up for us, we can use that state data to give a list of elements to React and let it do it’s thing. Inside the render method of our component, let’s return a list of items that the arbitraryStateData property (found on our state object) will generate.
render () {
return (
<div>
// map returns an array remember? So lets give react an array of JSX elements and let it perform it's magic. For this example we'll assume this list is a string.
{this.state.arbitraryStateData.map(data => <div>{data}</div>)}
</div>
);
}
One last thing to note is that any changes from setState invoke a call to our render method as well. We’ll discuss more on this later, but it’s important to remember that render() is called during mounting, and will be reinvoked if anything changes in our state object. You can think of the state object and render methods as existing together. The state object is like the bigger brother to the render function, it tells the render function what to do, and the render function obeys.
In conclusion, the render() method is how we tell React what data we want to turn into DOM elements. render() is necessary for every class component we create because we need it to return <JSX/> elements. It is involved in the Mounting Phase and the Updating Phase of our component’s lifecycle.
Continue to think about these methods as the mounting methods in our Component LifeCycle as you create more and more professional-looking code.
Let’s build out some friends together using this code sandbox link
Once there, you should see a page that renders out a <h1> and <p> tags. You should also notice a people.js file that contains an array of objects with this shape.
{
"id": 1,
"first_name": "Suzi",
"last_name": "Claiden",
"email": "[email protected]",
"occupation": "Biostatistician II",
"friends": [
{
"firstName": "Gabe",
"lastName": "Lemery"
}
]
}
This is the data that our application will consume. Using the knowledge of the React LifeCycle methods, we will discuss how to get this data from one place to another while.
Let’s start at the beginning with our constructor method. First, let’s define a name for our state data. Our data object is all about people, so let’s call our state object “persons” (intentionally not “people,” so that we can tell the two apart.)
Let’s import the people and set them up on our constructor’s state object.
import { people } from "./people";
...
constructor() {
super();
this.state = {
persons: people
};
}
...
Now that we imported data, we can loop over that friend’s array and generate a DOM element for each item in the array.
Now you’re going to extend the Friends App that we built together link by completing the following tasks.
- Notice that each person object has an array of friends assigned to it.
- The goal for the stretch problem will be to have a
FriendsListdrop-down built out that hides the friends for each person until it is clicked on. - Once a user clicks on your FriendsList card, display that user’s friends.
Understanding the timing of componentDidMount and utilizing that timing to ensure that your component has the state on it that you need when you need it, is pivotal in designing a proper functioning React application. Today we’re going to learn all about what componentDidMount is, when it gets called, and what we commonly do within it.
The componentDidMount method is a part of the mounting phase in the React Lifecycle. This method gets called as soon as the render method is called the first time, and it begs the question…now what?
When our component has mounted, we have the bare bones minimum we need to put something on the screen, so now what?
Inside of componentDidMount we can call setState which forces a re-render of our component. This way, any asynchronous actions should be performed inside of our componentDidMount function, especially when it comes to fetching data via HTTP. Data fetching is the de-facto purpose for using componentDidMount within a component because of its position within the component lifecycle.
This method is guaranteed to be called only once in the whole lifecycle , immediately after a component is mounted.
Until we know more about async AJAX calls, we’ll use componentDidMount to set up state data living in a separate file. We’ll do this by pulling the data in and setting it on state. This is also something you’re going to have to do for your “Insta-clone” assignment today.
Let’s now put some of our knowledge together and build a react component that consumes some data from a separate resource.
To follow along, go ahead and click on this link that will take you to a codesandbox.
Your index.js file should look a lot like this:
import React, { Component } from "react";
import { render } from "react-dom";
import CitiesList from "./CitiesList";
class App extends Component {
constructor() {
super();
this.state = {
cities: []
};
}
render() {
return <CitiesList />;
}
}
render(<App />, document.getElementById("root"));
We are merely importing in a component called CitiesList and returning it to the screen. CitiesList is a pure functional Component whose only responsibility is to render the props passed down to it on to the screen. We have two very different styles of components here.
The only problem is that CitiesList wants to render something out, in fact, right now, if you look at the console, you’ll see that props is an empty object. Our goal is to try and fix that.
Inside of the cities.js file, you’ll find a global object with a property data as an array of cities. Let’s import that into our index.js file and utilize the data.
import cities from './cities.js';
If we console.log our cities, you’ll see that we now have access to them. To fix the issue set forward earlier, we need to set this data on state and pass that data down as props to our CitiesList component. We’ll do this inside of componentDidMount
componentDidMount() {
this.setState({ cities: cities.data });
}
Use this function inside of a componentDidMount call in an app with a state object set up. Fetch a list of Dogs you can see their beautiful images.
const getDogs = () => {
fetch('https://dog.ceo/api/breed/labrador/images')
.then(res => res.json())
.then(dogs => this.setState({dogs: dogs.message}))
.catch(err => console.log('noooo'));
};
Once the dogs are on state. Build out a list of <img> tags that display each doggo.
If you get stuck this is what I’m going for
-
Rebuild the Github User Card app, but this time with React. In this project, you will fetch the data and manage state in class components.
You can use class recordings to help you master the material.
-
The React Lifecycle for Web35 w/ Warren Longmire
The React Lifecycle
To demonstrate mastery of this module, you need to complete and pass a code review on each of the following:
-
Objective challenge:
Read this medium article about the component lifecycle. Take notes and share what you learned in a paragraph to your Project Manager via Slack.
-
Objective challenge:
Now you’re going to extend the Friends App that we built together link by completing the following tasks.
- Notice that each person object has an array of friends assigned to it.
- The goal for the stretch problem will be to have a
FriendsListdrop-down built out that hides the friends for each person until it is clicked on. - Once a user clicks on your FriendsList card, display that user’s friends.
-
Objective challenge:
Use this function inside of a
componentDidMountcall in an app with a state object set up. Fetch a list of Dogs you can see their beautiful images.const getDogs = () => { fetch('https://dog.ceo/api/breed/labrador/images') .then(res => res.json()) .then(dogs => this.setState({dogs: dogs.message})) .catch(err => console.log('noooo')); };Once the dogs are on state. Build out a list of
<img>tags that display each doggo. -
Project: React Github User Card
