avatarHussain Arif

Summary

The provided content discusses the usage of class-based components in React.js, detailing how to implement states and lifecycle methods to manage and control the behavior of web app elements.

Abstract

The article "Class Based Components in React.js" delves into the creation and utilization of class components as an alternative to functional components for rendering JSX elements. It explains the necessity of class components for managing state changes and leveraging lifecycle methods, which are not available in functional components. The author illustrates the process of defining class components by extending React.Component, initializing state within the constructor, and using the setState method to update state values. The article also covers event handling to dynamically change state values and introduces essential lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount to manage component behavior throughout its lifecycle. Practical examples and exercises are provided to demonstrate incrementing state values and the importance of lifecycle methods for resource management and preventing memory leaks. The article concludes with a recap of the concepts and encourages further reading and practice to master React component development.

Opinions

  • The author emphasizes the importance of understanding class components for working with legacy code, suggesting that developers will inevitably encounter them in their careers.
  • Class components are presented as more powerful than functional components when it comes to controlling elements through states and lifecycle methods.
  • The use of this.setState is highlighted as the correct approach to change state values, as opposed to directly mutating this.state.
  • The article suggests that proper use of lifecycle methods is crucial for professional React development, particularly for resource cleanup and avoiding memory leaks.
  • The author advocates for self-study and hands-on practice, encouraging readers to play with the code and not give up in their learning journey.

Class Based Components in React.Js

How to Implement States and Lifecycle Methods in Your Web App

Source: Jake Blucker On Unsplash.com

In my previous articles, I’ve extensively used functional components to create JSX elements in React. However, apart from using the functional component method, there is another way to materialize JSX components; they’re called class components.

In this article, we will discuss

  • Why to use class components over their functional counterparts?
  • How to create class components and utilize them in our React program.

Introduction

Why to use Class Components?

  • To illustrate, let’s use an example. Here, we want to display the color of the car using functional components
function Car() {
return(
  <h1> Car Color : {props.color} </h1>
)
}
ReactDOM.render(<Car color="blue"/> , document.getElementById('root'))

This is a fairly basic functions and props example. However there’s just one problem : What if I want to change the value of the prop with the click of a button?

The answer is: you can use hooks in your functional components. However, during your career, you will be dealing with legacy code, so there will be days where you would be dealing with class components. To curb this problem though, we use a concept called states. These states are only accessible via the creation of class based components.

  • One more advantage is lifecycle methods. They are basically functions which allow you to control what happens throughout the lifespan of an element, for instance, display a timer whenever an element is ‘born’ and so on and so forth.

In short, class based components give you extensive control over your element.

Basic Usage

To write a class component:

  • First import the Component class from "react" package:
import React,{Component} from "react"

You can now use the React.Component capabilities in your app.

  • Now you have to extend the properties of React.Component in your class. This is done through the extends keyword.
import React,{Component} from "react"
import ReactDOM from "react-dom"
class MyComponent extends Component {
render() {
return(
<h1> Hello world </h1>
 )
}
}
ReactDOM.render(<MyComponent/> ,document.getElementById('root'))

The definition of the component is bolded. The steps are as follows:

  • MyComponent simply inherits from the React.Component class.
  • The render() method is called to display the element into the browser. render() is essentially a lifecycle method. This is one of the few things that is new information in creating class based components.

This is the result:

The output of the code

Let’s move further to using props in class components.

How to Use Props in Class Components

In functional components, this is how you would implement props:

function MyComponent(props) {return(
<h1> {props.color} </h1>)
}
ReactDOM.render(<MyComponent color="function"/> , document.getElementById('root'))

However in classes,

class MyComponent extends Component {
render(){
return (
<h1> {this.props.color} </h1>
)
}
}
ReactDOM.render(<MyComponent color="class"/> , document.getElementById('root'))

Notice that

  • In function components, it is props.color
  • However in class components, it is this.props.color

Note: This means that: when using props in class components, always use this keyword

This is the result:

Code output for using props in classs

What if you want to change a prop through code? This seems like a huge problem. The browser might throw an error if you type the following code:

this.props.color = 'yellow' //wrong

This is where a concept called states come in. Let’s move on to the next step.

Adding Local States to a Class

How do states and props differ?

In a React component, props are variables passed to it by its parent component. State on the other hand is still variables, but directly initialized and managed by the component.

Whenever the state is changed, the component that contains the state will re-render on the screen.

Basic Usage

To declare a state, you do the following:

  • Step 1: Declare a constructor for your class component and use super()
class MyComponent extends Component {
constructor(props) {
  super(props)
  • Step 2 : Add properties and values to the this.state object. This is to be done within your constructor
this.state = {
  property : 'value'
}
} //this marks end of constructor
  • Step 3 : To display the value of this property, use simple JSX.
render() {
  return(
  <h1> {this.state.property} </h1>  
  )

That’s all there is to it. Finally, the code will look like this in the end,

This will be the output in the end:

Code output for displaying states

Let’s move on to changing the state values

Event Handling To Change States Dynamically

As an example, let’s say that we want to change the text in a paragraph with the click of a button. As discussed, we can change states through scripting, so that’s what we’ll use.

Basic Usage: setState method

We will be reusing our previous state example.

There is a designated way to change states. To change state, we use this.setState() method. Let’s change the property property to 'hussain'

this.setState({property: 'hussain'})

The above code line is right, however this snippet below is wrong, so avoid using this method:

this.state.property = 'hussain' //wrong
this.setState({property:'hussain'}) //right

To implement event handling,

  • Create a method , handleClick and use setState() method
handleClick() {
    this.setState({property:'hussain'})
  }
  • You want to now tell React that handleClick will change state values. To do so, go to your constructor definition and write this in the end:
this.handleClick = this.handleClick.bind(this)
  • Let’s implement a button that will call handleClick function. Do this in the render method:
<button onClick={this.handleClick}> Change value </button>

This will be the code output:

(left to right):before clicking the button and after clicking the button

Ultimately, the code will look like this:

Let’s say you want to change the values of the propertystate back and forth,

This is possible, this.setState also takes in a callback function. This function’s single parameter has all the previous values of the state.

Modify handleClick like so:

handleClick() {
    this.setState((previousState)=>{
      if(previousState.property==='value') 
        return {property : 'hussain'}
      return {property: 'value'}
    })
  }

Explanation: The previousState variable contains the previous values of the state variables. This piece of code compares whether the value of property is value . If it fulfills this requirement, change the value of property to hussain . Otherwise, change it to value .

You can see the output in this GIF:

Toggling between values in React

Exercise

As an exercise, I want you to

  • Increment a value of a state variable with the click of a button.
  • Display this state variable

Solution

We can

  • Create a state variable, number and then write a function to increment number
  • Call this function when a button is clicked

The code will be as follows:

The output of the code is demonstrated by this GIF:

Output showing the result when button is clicked

Let’s say we want to control the element as it goes throughout its lifespan. For example, display a message when the element has rendered to the DOM and so on and so forth. This is explained in the next section.

Lifecycle Methods

As a professional developer, it’s common for you to have a multitude of elements in your app. Thus it’s very important to free up the resources when a component is destroyed. For example, when a textfield is deleted, you want to delete other buttons along with that textfield.

There are two terms you should know.

  • Mounting : Whenever an element is ‘born’ or displayed to the DOM for the first time, it is mounted.
  • Unmounting : Whenever an element is deleted off the DOM, it is unmounted.

Some notable methods are :

  • render() : Like getting dressed for the day. Executes when a component is displayed to the world. Executes multiple times when states are changed.
  • componentDidMount() : This is like saying that the component is now born. It only runs once. In this method, you should fetch the data you need to correctly display, for example data from an API or a server.
  • componentWillUnmount() : run just before the component is deleted. In this method, you can tear down your code before the component disappears. Useful if you want to remove all of the intervals associated to that component. It’s practical for preventing memory leaks.
  • componentDidUpdate() : is invoked immediately after updating occurs. This method is not called for the initial render.

To show you an example, let’s reuse our code from our previous exercise in the previous section, where a number was being incremented every time a button was clicked.

To the MyComponent class definition, add the following two methods:

componentDidMount(){
console.log('component mounted');
}
componentDidUpdate() {
console.log('component updated');
}

Now add these lines to the render method

render() {
return(
  //.. other code
 {console.log('rendering')}
)
}

This means that whenever MyComponent starts up, updates or renders to the screen, the messages are displayed accordingly.

This is the output in the end:

Output of the code : Notice the logs whenever the button is clicked

Notice how the relevant information is displayed whenever the button is clicked. Observe that render() is called multiple times, and that componentDidUpdate() is called whenever the component is updated.

Recap

  • Converting a functional component with props to class component with props:
  • To set states
  • To change states:
  • componentDidMount runs whenever the component is first displayed to the DOM
  • componentWillUnmount runs whenever the component is destroyed
  • render is run multiple times whenever the component is first displayed, or updated.

Resources/Further Reading

Conclusion

This post covers all the basics you need to know about creating class based components in React. To dive more in depth, you should see the links provided above. Self study is essential if you want to become a skilled developer.Play with the code and deconstruct the examples. Just don’t give up.

In the end, I hope you’ve learned a bunch about this topic. Thank you so much for making it to the end! Have a great day.

Next post : How to Create Forms in React Here’s my previous post : A Guide to Props in React

Programming
JavaScript
Web Development
Education
Technology
Recommended from ReadMedium