DEV Community

Siddhartha Mishra
Siddhartha Mishra

Posted on

Class Based React

If you are a new React developer then most probably you will be using functional based Approach for React components. But if you are an old React Developer then most likely you have used Class based Approach for React Components or might be still using.
Now there are many debates that functional based approach is better than class based approach and vice-versa. But it's not as simple as that. Different scenarios need different approaches. It is not a rule of line that you have to only use one approach and denounce other one rather it is better to have understanding of both approaches.

Class based approach

It uses ES6 Classes for defining components. If you are familiar with functional based approach then, you know that, it uses functions to define the component. In case of class based approach, all class components are extended form of React.Component. Extending React.Component class allows user to use prebuild API's. Basic App component in Class based React looks like :

import React from "react"
class App extends React.Component{
  render(){
    return <h1>Hello World!</h1>
}
export default App;
Enter fullscreen mode Exit fullscreen mode

What about Hooks

Technically you can use hooks with classes. But it takes away the features of Class Based Approach. Nearly all functionality of hooks can be achieved using classes.
In rare scenarios you are bound to use hooks for achieving a functionality with ease. If you are familiar with basic hooks in React then, you will not find any difficulty in grasping the Class implementation. For Example - instead of useState() we use this.state and setState().

Now , I'll try to explain how simple functionalities of useState() and useEffect() hooks are achieved using classes.

constructor()

Before learning about state management, it is very crucial to get the gist of constructor(). Basically constructor() are the methods that are called when object of Class is initialized. This method is used to setup state of the Component with initial values.

In the constructor another method that is important is super method. By calling this method we get access to methods and states of parent classes in which this is called. This method is useful for accessing props in the Component.

import React from "react"
class App extends React.Component {
  constructor(props) {
    super(props)
  }
  return <h1>Hello World!</h1>
  }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Counter App

Now lets try to implement counter in Class based Approach. If you are familiar with hooks, then implementing this functionality will cost no effort.

We will start by defining state. In the Component

constructor(props){
  super(props)
  this.state = {
  count:0
 }
}
Enter fullscreen mode Exit fullscreen mode

For changing the value of count,we will be using setState() method . As

this.setState({count:this.state.count+1})
this.setState({count:this.state.count-1})

Our basic Counter App is ready.
Complete code

import React from "react";

class App extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }
  render() {
    return (
      <>
        <h1>{this.state.count}</h1>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          +
        </button>
        <button onClick={()=>this.setState({count:this.state.count-1})}>
          -
        </button>
      </>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In the above code we initialize count state and change its value using setState() method. It is very similar to useState() hook. this keyword is typically used here to bind method with its corresponding class.

Data fetching

In functional based approach, we use useEffect() hook to fetch data from the API. Typically this hook is used for side effects in the web application. Because we don't want to stop the rendering of page, therefore we fetch data as a side effect.
In class based approach we use componentDidMount() method . It allows user to perform actions when component is rendered on the webpage. If you deep dive into both the methods then, they are very different to their core, but for achieving these types of functionality, they work pretty much identical.
Now let's learn it by the code-
In this example , I will be using DummyJSON product API. You can get it here

First we will create a fetching function as

fetchData=async()=>{
  const response=await fetch('https://dummyjson.com/products')
  const result = await response.json()
  this.setState({products:result})
}

Enter fullscreen mode Exit fullscreen mode

In this example, I'll be storing the result in products state.

Now it's time to call fetchData() method so that it doesn't block rendering of the page.

 componentDidMount(){
    this.fetchData()
  }
Enter fullscreen mode Exit fullscreen mode

For the products state

constructor(props){
 super(props)
 this.state={
  products=[];
 }
}
Enter fullscreen mode Exit fullscreen mode

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { products: [] };
  }

  fetchData = async () => {
    const response = await fetch("https://dummyjson.com/products");
    const result = await response.json();
    this.setState({ products: result });
  };

  componentDidMount() {
    this.fetchData();
  }

  render() {
    console.log(this.state.products);
    return (
      <>
        <h1>Data fetching</h1>
      </>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

console

console log of the products state

That's it, now you know the basic concept of class based approach to react. I tried my best to explain the concept. Hope you learnt a lot.

References -
react.dev
super and props

For any queries , connect with me here

Top comments (0)