Three identical links need not be written three times. Define a class component once, then create three elements from it. A class component extends React.Component and supplies a render method that returns the elements to display. section 2.4
Listing 3.4 Three identical links with JSX
import { Component, Fragment } from 'react';
class Link extends Component { #1
render() {
return (
<p>
<a href="//react.dev">Read more about React</a>
</p>
);
}
}
class App extends Component {
render() {
return ( #2
<Fragment> #3
<Link /> #4
<Link /> #4
<Link /> #4
</Fragment>
); #5
}
}
export default App;
The Link class renders one paragraph and link. App renders three Link instances using JSX; capitalized names distinguish custom components from standard tags. section 3.2.2
A class component can also receive data and respond to changes:
- Read a passed property through this.props, such as this.props.title. Do not change properties inside the component. section 2.7 section 4.4.3
- Store changing values in the single this.state object. Call this.setState to update it; a partial update merges with the existing state. section 5.3 section 5.3.2
- Unlike useState, calling setState can re-render a class component even when the values have not changed. section 5.3.2
A click counter
With `import { Component } from 'react'`, a small counter is `class Counter extends Component { state = { counter: 0 }; render() { return <button onClick={() => this.setState({ counter: this.state.counter + 1 })}>Clicks: {this.state.counter}</button>; } }`. The displayed count comes from state, and the click handler updates it through setState. section 5.3
Class components can also use lifecycle methods to respond to mounting, updates, and unmounting, although these methods are more complex than their functional-component counterparts. An error boundary is a particular reason to use a class: getDerivedStateFromError can change its fallback rendering, while componentDidCatch provides error information for logging. section 6.0 section 4.3.1
For a new project, start with functional components unless a class-specific need arises. Both component types remain supported; choosing a class does not inherently make a simple component slower, less accessible, or less reusable. Classes are also common in older codebases. section 4.6 section 4.2.3

