18 Apr 2023

React Component State

  • setState schedules an update to a component’s state object. When state changes, the component re-renders.
  • Calls to setState are asynchronous for performance reasons.

Example

// Assume count starts at 0

incrementCount() {
  this.setState({count: this.state.count + 1});
}

handleSomething() {
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();

When react re-renders this component the state will be 1 even though we called it three times.

→ Why? React doesn’t update this.state.count until the component is re-rendered. incrementCount() ends up reading count as 0 three times.

Fix: Pass an update function:

incrementCount() {
  this.setState((state) => {
    // Use state, not this.state cause it's a parameter
    return {count: state.count + 1} 
  });
}

Difference between state and props

  • both plain JS objects
  • props get passed to the component (similar to function parameters)
  • state is managed within the component