React › Class Components & Legacy Lifecycle Methods

How do you set and update state correctly inside a class component?

Beginner

Answer

State is first defined inside the constructor using this.state as a plain object. To change it later, you always call this.setState with the new values, and React will re render the component automatically. You should never change this.state directly, since that will not trigger a re render.
class NameForm extends React.Component {
  state = { name: '' };
  handleChange = (event) => {
    this.setState({ name: event.target.value });
  };
  render() {
    return <input value={this.state.name} onChange={this.handleChange} />;
  }
}
Real-world example A simple contact form built with a class component updates the name field's value every time the user types, using this.setState to keep the input and the component's state in sync.

Common follow-ups: What happens if you try to update state by writing this.state.name directly instead of using setState?;How is updating state with setState different from updating state with the useState hook?