Forgot React Class Components? Let Me Help

Hello, React developers! Are you one of those devs who only remembers/knows how to write functional components but not class components? Chances are, yes. The reason is with the introduction of React Hooks (which can only be used in functional components), developers have started to disregard class components. The problem is you will almost always find class components in existing React codebase (especially if it belongs to a large company). In this article, I will give you the shortest crash course on class components.

[1] Creating Class Components and Accessing Props

class App extends Component {
  render() {
    const { theProp } = this.props;
    return (
      <div>{theProp}</div>
    );
  }
}

This is the template for creating a class component and accessing props. As you can see, knowledge of the "this" keyword in JavaScript is important to work with class components.

[2] State

class App extends Component {
  state = {
    items: [],
    total: 0
  }

  render() {
    return <h1>The first item is {this.state.items[0]}</h1>
  }
}

In class components, you cannot use the new and powerful useState. To create a state, assign state to an object which would contain the state data. Again, the "this" keyword makes the code look less elegant.

[3] Handlers

class App extends Component {
  state = {
    items: [],
    total: 0
  }

  handleClick = () => {
    this.setState({
      total: 99
    })
  }

  render() {
    return (
      <div>
        <h1>The first item is {this.state.items[0]}</h1>
        <button onClick={this.handleClick}>Add</button>
      </div>
    )  
  }
}

In an event handler in a class component, you need to use the setState method and override the existing state's data. In this case, we are only setting the total to 99 which means only the total value will change from the existing state (items value will still remain the same).

[4] Lifecycle Hooks

These are not the shiny new React Hooks like useEffect, useState and so on. However, keep an eye on componentDidMount() (similar to useEffect), componentWillUnmount() (clean up function), and componentDidUpdate().

7