Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of using classes in React?

I mostly see JavaScript use classes as a constructor as following:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

What's the reason React uses classes without using the contructor() function, such as following? I don't see classes being used to create instances.

class App extends Component {

    render() {
        return (
            <div className="app-content">
            </div>
        )
    }
}
like image 879
Kevvv Avatar asked Dec 11 '22 03:12

Kevvv


1 Answers

Right now you should use classes in React if you need to use "advanced" component lifecycle methods like shouldComponentUpdate() or such.

Previously class components were used to handle local state in them. Right now we have Hooks API which allows to use state in a more elegant way and without need of class components.

If you want more details, you can read the article by Dan Abramov: How Are Function Components Different from Classes?.

Regardless your example, you're right, this code:

class App extends Component {

    render() {
        return (
            <div className="app-content">
            </div>
        )
    }
}

can be written as:

function App() {
  return <div className="app-content"></div>
}
like image 200
flppv Avatar answered Dec 12 '22 15:12

flppv