Working with States and Events
In a class based React component, state is an object stored on this.state that holds data which can change, and events are user actions such as clicks or typing that trigger methods on the class. Combining the two is how class components become interactive: an event handler calls this.setState(), React re-runs render(), and the screen updates. You will meet this pattern in older codebases and when reading existing React projects.
Setting up initial state
State is created either in the constructor or with a class field. In the constructor you must call super(props) first, otherwise this is not available.
import { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0, step: 1 };
this.handleIncrement = this.handleIncrement.bind(this);
}
handleIncrement() {
this.setState((prev) => ({ count: prev.count + prev.step }));
}
// Class field arrow function: no bind needed
handleStepChange = (event) => {
this.setState({ step: Number(event.target.value) });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<label>
Step:
<input
type="number"
value={this.state.step}
onChange={this.handleStepChange}
/>
</label>
<button onClick={this.handleIncrement}>Add</button>
</div>
);
}
}
export default Counter;
How setState really behaves
setState does not replace the whole state object. It merges the object you pass into the existing state, so updating step leaves count untouched. This is different from the useState hook, where each setter replaces its own value.
Updates are also not applied instantly. React may batch several setState calls together and re-render once. Reading this.state right after calling setState can give you the old value. When the new state depends on the old one, pass a function, as handleIncrement does above. React calls it with the latest state, so three quick clicks always add three steps. If you need to run code after the update has been applied, setState accepts a second argument, a callback that runs after the re-render.
Connecting events to methods
React events use camelCase names like onClick, onChange and onSubmit, and you pass a function reference, not a string. The handler receives a synthetic event object that works the same in every browser, with familiar properties like event.target and methods like event.preventDefault().
To pass extra data, wrap the call in an arrow function: onClick={() => this.removeItem(item.id)}. Writing onClick={this.removeItem(item.id)} would call the method during render instead of on click.
The two bugs everyone hits
"Cannot read properties of undefined (reading 'setState')". Class methods are not bound to the instance automatically. When React calls your handler, this is undefined. Fix it by binding in the constructor, as with handleIncrement, or by defining the handler as an arrow function class field, as with handleStepChange. Arrow functions take this from the surrounding class.
Changing state directly. Writing this.state.count = 5 changes the value but does not tell React, so nothing re-renders. The only exception is the initial assignment in the constructor. Everywhere else, use setState. The same goes for arrays and objects inside state: create new copies with spread syntax instead of calling push on the existing array.
Summary of the pattern
- Initialise
this.statein the constructor or as a class field. - Write handler methods and make sure
thisis bound. - Call
this.setState(), using the function form when building on previous values. - Read from
this.stateinsiderender().
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.