Why this.setState method in class in React works without being called?

Tell us what’s happening:

Hi, I’m totally new to React.js and fully don’t get why this.setState method in React Class component works without being called.

In pure JS, method defined in class has to be called if users want to use the method. But in below codes, componentDidMount method (I don’t even know if this is called as method though) is not called from anywhere but it works perfectly.

Please kindy help me to understand.

Your code so far

class MyComponent extends React.Component {
constructor(props) {
  this.state = {
    activeUsers: null
componentDidMount() {
  setTimeout( () => {
      activeUsers: 1273
  }, 2500);
render() {
  return (
      <h1>Active Users: { this.state.activeUsers }</h1>

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36.

Challenge: Use the Lifecycle Method componentDidMount

Link to the challenge:

It’s all right here extends React.Component.

This line right here says that MyComponent is extending the class React.Component, what that means is that it inherits all of the properties and methods declared in React.Component, one of which is called setState, which is why you can use it here.

1 Like

Scroll down a bit to the section titled Inheritance with class syntax.