loading...
Cover image for Just How Do React.js Components Cycle Through Life?

Just How Do React.js Components Cycle Through Life?

jamesfthomas profile image James F. Thomas ・6 min read

The Lifecycle of React.js components!

A “Lifecycle” in the React.js framework refers to the procedures which correlate to the creation, displaying, monitoring, and removing of a React component. This “Lifecycle” can be arranged into three phases – Mounting, Updating, Unmounting – with various methods available on the React object that empower a developer to observe and alter the component as desired throughout each section of its life. So, let us take a quick peek at the birth, life, death, and the associated tools for each phase in the lifecycle of a React component.

So how do I bring a component to life?

The birthing of a React.js component comes about in the mounting phase of the lifecycle. While it does refer to the first stage of this component's life it can be broken down one step further as well to include different steps according to the type of component you want to bring to life. Before mounting your component, you must consider the desired tasks you want this component to perform on the page, which will influence your choice to initialize the component with or without state. State is an object that is given to your component via the constructor and allows you to set properties on the component that can be monitored for changes.
The state object is a JS object so accessing and setting those properties is done via dot notation. A stateless component also referred to as presentational or dumb, is labeled this chiefly because these components lack a state object and cannot track changes in user information. The stateless components are used to present or display static (unchanging) information. Stateless components due to one thing hence the names presentational and dumb.

Stateless Components

1
//Will display basic stateless React.js element

ReactDOM.render(
<h1> Completely Statless Yall </h1>, 
document.getElementById("htmlLocation")
);
2
const Stateless = () => {
  return (
    <h1>All I Do Is show This Info!</h1>
  )
 }

//Will display basic stateless functional React.js component 
ReactDOM.render(
<Stateless />, 
document.getElementById("htmlLocation")
);

3
class Stateless extends React.Component {
 constructor(props) {
   super(props)

  }
 render() {
   return(
     <div>
      <h1>{this.props.title}</h1>
     </div>
   )
 }
}

var info = {
  title: "I have no state"
} 

//Will display basic stateless React.js class component  
 ReactDOM.render(
  <Stateless title={info.title}/>, 
  document.getElementById("htmlLocation")
  );

Statefull Component

class CodeSchools extends React.Component {
  constructor(props) {
    super(props);
    this.state = {school: "Operation Spark"};
  }
  render() {
    return (
      <div>
        <h1>Welcome To {this.state.school}</h1>
      </div>
    );
  }
}

//Will display stateful React.js class component
ReactDOM.render(
  <CodeSchools/>, 
  document.getElementById("htmlLocation")
  );


React.js elements evolve into components once they begin to accept props object regardless if they have state or not. There is a guiding rule in react.js, that will affect how you interact with the props object that you pass into your stateful components, which all pertain to purity. No matter if the component you declare is of the functional or class designation it must never alter its own props. Remember that in JS a pure function does not alter its inputs and has the same return value for the same inputs, well the same rules apply to any component in the React.js framework.

// impure function example 

function impure(object, name) {
  object.owner = name;
  return object;
}

Side-Information

In React.js the act of placing your initialized component or element on the DOM is called Mounting and is the second part of the first stage of the lifecycle but is usually the term used to describe both actions. So, in the future, if you come across mounting remember you must first create something before it can be placed. For the mounting Phase to be carried out React.js has multiple built-it methods that can be employed to get your component onto the screen but only one is absolutely necessary, and that is rendered (). The render method is the portion of your component that will actually output HTML elements to the DOM, it will examine the components state, and then return elements, fragments(a group of child elements like a list), portals (render components to different parent component), or basic JS data values (strings && numbers). There are additional Mounting phase methods such as componentDidMount (allows you preset JS statements to alter the state of the object once it has mounted), but to best illustrate the key actions of this phase I will stick to highlighting the render() method only.

So, what happens after my component is mounted?

After the mandatory render method has placed your React.js component onto the DOM, you have officially entered the Updating phase of the component’s lifecycle. During the updating phase, the component will be rendered repeatedly according to either a change in the parent components props object or a change in the components local state. These changes represent interactions with the user interface or updating of information from a server that is being visually represented on the DOM. Methods like setState() allow us to interject event listeners into our components that will change the state properties in response to desired events. One common example would be changing DOM information in response to a user click.

class CodeSchools extends React.Component {
  constructor(props) {
    super(props);
    this.state = {school: "Operation Spark"};
  }

/*
created new function which uses setState() method to 
change school name property of state object
*/
  changeSchool = () => {
    this.setState({school: "Hack Reactor"})
  }

  render() {
    return (
      <div>
        <h1>Welcome To {this.state.school}</h1>
<!--added HTML button & click listener responds to user actions-->
        <button type="button" onClick={this.changeSchool}>Change Your School</button>
      </div>
    );
  }
}

There are multiple methods that will allow you to monitor and subsequently change your component in response to that input but setSet() is very simple far simpler for a beginner to grasp in theory and implementation so I kept it simple in the above example. If you just need to know more about component updating you can go to https://reactjs.org/ and read up on the methods shouldComponentUpdate(), ComponentWillUpdate(), and componentDidUpdate() to satisfy your curiosity.

It’s up and updating, so now what?

Once the component is up and responding to user interactions, we can move along into the final lifecycle phase which encompasses removing components from the DOM and so is appropriately named in direct opposition to our first phase. We are now in the Unmounting phase of the react.js component lifecycle which is home to one solitary built-in method, componentWillUnmount(). Following the appropriate naming of the phase, this method’s only job is to remove a component from the DOM in preparation for being destroyed. Once a components instance is taken off the DOM or unmounted it will never be rendered again. In light of this fact componentWillUnmount() should not utilize the updating phase method of setSet() because the component will never be used again and therefore will have no state to set.

//This function will alert you right before the component is removed and destroyed 

componentWillUnmount() {
  console.log('will unmount');
}

ComponentWillUnmount() is the final function to be called in a chain of events prior to your component being removed from the DOM. It can be used to simply alert you of the component’s removal or be set to do away with or cancel any elements as well as timers set in the mounting phase by built-in method like CompentWillMount() or CompentDidMount(). Since we are keeping this exploration of the lifecycle phases as a basic overview, I feel simply alerting you to the existence of the method is enough to properly demonstrate each phase and some of the methods employed in each one.

Conclusion

The lifecycle of any component in React.js is split into 3 distinct phases which are all eloquently named for your ease of recall. If you think about them logically you will never miss one in the set when asked. First, create it and put it on the screen. Second, monitor and change accordingly. Third and final, remove and destroy when done.

Topic Recap:

  • Components are not components until the accept props

  • Components need to be pure not altering inputs, returning the
    same value with same input

  • The component Lifecycle is composed of three main parts:
    Mounting, Updating, Unmounting

  • Unmounting has only 1 built-in method for that lifecycle phase

If this overview was not enough to elucidate the cycles of a react.js component’s life for you, check out the links below for a deeper dive into aspects and methods that are coupled with each stage. Until next time and topic, Happy coding!

Sources:

Posted on by:

jamesfthomas profile

James F. Thomas

@jamesfthomas

Just beginning my journey into the world of computer program. Started off with self taught lessons, now in a bootcamp.

Discussion

markdown guide