Class Components

and Lifecycles

Class Components

As opposed to functional components, class components are classes that

  • inherit from React.Component and
  • override at least the `render` method

Why class components?

  • Another way to write a component instead of functions
  • At times, class components can give you finer control on the workings of the component
  • From the usage point of view, there's no difference between Functional and Class components

Example

function Counter() {
  return (
    <div>
      <h1>0</h1>
      <button>Inc</button>
    </div>
  );
}

<Counter />
class Counter extends React.Component {
  render() {
    return (
      <div>
        <h1>0</h1>
        <button>Inc</button>
      </div>
    );
  }
}

<Counter />

Example

function Counter(props) {
  const { startFrom } = props;
  return (
    <div>
      <h1>{startFrom}</h1>
      <button>Inc</button>
    </div>
  );
}

<Counter startFrom={32} />
class Counter extends React.Component {
  render() {
    const { startFrom } = this.props;
    return (
      <div>
        <h1>{startFrom}</h1>
        <button>Inc</button>
      </div>
    );
  }
}

<Counter startFrom={32} />

Example

function Counter(props) {
  const [num, setNum] = 
        useState(props.startFrom)
  return (
    <div>
      <h1>{num}</h1>
      <button>Inc</button>
    </div>
  );
}

<Counter startFrom={32} />
class Counter extends React.Component {
  state = {
    num: 0
  };
  render() {
    return (
      <div>
        <h1>{this.state.num}</h1>
        <button>Inc</button>
      </div>
    );
  }
}

<Counter startFrom={32} />

Example

function Counter(props) {
  const [num, setNum] = 
        useState(props.startFrom);
  return (
    <div>
      <h1>{num}</h1>
      <button
        onClick={function () {
          setNum(num + 1);
        }}
      >
        Inc
      </button>
    </div>
  );
}
<Counter startFrom={32} />
class Counter extends React.Component {
  state = {
    num: this.props.startFrom
  };

  handleClick = () => {
    this.setState({ num: this.state.num + 1 });
  };

  render() {
    return (
      <div>
        <h1>{this.state.num}</h1>
        <button 
      	  onClick={this.handleClick}
        >
          Inc
        </button>
      </div>
    );
  }
}

<Counter startFrom={32} />

Core syntactical differences

functional class
props as argument to the fn on the `this` with key `props`
inherit nothing React.Component
type function class
state useState `this.state` in the constructor
update state using the 2nd function returned from useState using `this.setState` in a function / method

Lifecycles

  • We can declare special methods on the component class to run some code when a component mounts and unmounts: These methods are called “lifecycle hooks”.
  • Every Component follows a cycle from when it’s created and mounted on the DOM to when it is unmounted and destroyed. This is what we refer to as the Component lifecycle.
  • Our lifecycle is broadly categorized into three parts:
    • Mounting
    • Updating
    • Unmounting.

In short

Mounting

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Avoid

  • componentWillMount()

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:

constructor

Typically, in React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.

You should not call setState() in the constructor().

render()

The render() method is the only required method in a class component.

The render() function should be pure, meaning that it does not modify component state.

  • React elements <div />
  • Arrays and Fragments  [] / <> </>
  • React.Portals
  • String and numbers
  • Booleans or null. Render nothing.

componentDidMount()

  • This method is available after the component has mounted. That is, after the HTML from render has finished loading.
  • This is the best place to make API calls since, at this point, the component has been mounted and is available to the DOM.
  • So here is a bunch of things you can do with this method:
    • Connect a React app to external applications, such as web APIs or JavaScript frameworks.
    • Set Timers using using setTimeout or setInterval.
    • Add event listeners.
    • Draw on an element you just rendered.

Updating

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

Avoid (they are old lifecycle methods)

  • componentWillUpdate()
  • componentWillReceiveProps()

componentDidUpdate(prevProps, prevState, snapshot)

It is invoked immediately after updating occurs. This method is not called for the initial render.

You can use this method to do side-effects based on prop values. Just like componentDidMount

Unmounting

This method is called when a component is being removed from the DOM:

componentWillUnmount()

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.

Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

Once a component instance is unmounted, it will never be mounted again.

Class Components and Lifecycles

By Arfat Salman

Class Components and Lifecycles

  • 780