React Class Components - rs-hash/Senior GitHub Wiki

React Class Components

import { Component } from 'react';

class Counter extends Component {
  state = {
    age: 42,
  };

  handleAgeChange = () => {
    this.setState({
      age: this.state.age + 1 
    });
  };

  render() {
    return (
      <>
        <button onClick={this.handleAgeChange}>
        Increment age
        </button>
        <p>You are {this.state.age}.</p>
      </>
    );
  }
}
  • Class components are still supported by React, but they don’t recommend using them in new code.
  • To define a React component as a class, extend the built-in Component class and define a render method. Only the render method is required, other methods are optional.
  • this.context in class components is equivalent to useContext in function components.
  • The props passed to a class component are available as this.props.
  • Defining state in class components is equivalent to calling useState in function components.

Class component Lifecycle Methods

Constructor()

With and without constructor

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // ...
  }



class Counter extends Component {
  state = { counter: 0 };

  handleClick = () => {
    // ...
  }
  • The constructor runs before your class component mounts (gets added to the screen).
  • Typically, a constructor is only used for two purposes in React. It lets you declare state and bind your class methods to the class instance
  • If you use modern JavaScript syntax, constructors are rarely needed. Instead, you can rewrite this code above using the public class field syntax which is supported both by modern browsers and tools like Babel
  • Do not run any side effects or subscriptions in the constructor. Instead, use componentDidMount for that.
  • constructor should not return anything.
  • Inside a constructor, you need to call super(props) before any other statement. If you don’t do that, this.props will be undefined while the constructor runs, which can be confusing and cause bugs.
  • Constructor is the only place where you can assign this.state directly. In all other methods, you need to use this.setState() instead. Do not call setState in the constructor.
  • When you use server rendering, the constructor will run on the server too, followed by the render method. However, lifecycle methods like componentDidMount or componentWillUnmount will not run on the server.
  • When Strict Mode is on, React will call constructor twice in development and then throw away one of the instances. This helps you notice the accidental side effects that need to be moved out of the constructor.

componentDidCatch()

  • If you define componentDidCatch, React will call it when some child component (including distant children) throws an error during rendering. This lets you log that error to an error reporting service in production.
  • There is no direct equivalent for componentDidCatch in function components yet. If you’d like to avoid creating class components, write a single ErrorBoundary component.Alternatively, you can use the react-error-boundary package which does that for you.

componentDidMount()

  • If you define the componentDidMount method, React will call it when your component is added (mounted) to the screen. This is a common place to start data fetching, set up subscriptions, or manipulate the DOM nodes.

If you implement componentDidMount, you usually need to implement other lifecycle methods to avoid bugs. For example, if componentDidMount reads some state or props, you also have to implement componentDidUpdate to handle their changes, and componentWillUnmount to clean up whatever componentDidMount was doing.

⚠️ **GitHub.com Fallback** ⚠️