Before React 16.8, class components were the primary way to manage state and lifecycle in React. With Hooks, function components now offer similar capabilities. While function components are preferred, class components remain a valid option and are not being removed.
This section provides an overview of using class components in React.
Feel free to skip this section and use function components instead.
React Components
React components are reusable, independent pieces of code that return HTML via the render()
method. Components can be class or function components. This chapter focuses on class components.
Defining a React Class Component
To create a class component, you extend React.Component
. In this example, the Hello
component extends React.Component
and uses the render
method to return JSX. JSX allows you to write HTML-like syntax within your JavaScript code.:
class Hello extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } }
Using Props in Class Components
Props allow you to pass data between components. Here’s a simple example of using props in a class component.
In the Welcome
component, this.props.username
accesses the username
prop passed to the component.
class Welcome extends React.Component { render() { return <h2>Welcome, {this.props.username}!</h2>; } }
Managing State in Class Components
State allows a component to create and manage its own data. When the state changes, the component re-renders. Here’s a simplified example of using state in a class component.
In this example, the Counter
component has a state object with a count
property. The increment
method updates the state, causing the component to re-render and show the new count.:
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
Lifecycle Methods in Class Components
React class components have several lifecycle methods that allow you to run code at specific stages of a component’s life. Common lifecycle methods include:
componentDidMount()
: Runs after the component is first rendered.componentDidUpdate(prevProps, prevState)
: Runs after the component updates.componentWillUnmount()
: Runs just before the component is removed from the DOM.
In the Timer
component, componentDidMount
sets up a timer to call the tick
method every second, updating the state. componentWillUnmount
clears the timer when the component is removed from the DOM.:
class Timer extends React.Component { constructor(props) { super(props); this.state = { seconds: 0 }; } tick = () => { this.setState((state) => ({ seconds: state.seconds + 1, })); }; componentDidMount() { this.interval = setInterval(this.tick, 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return <div>Seconds: {this.state.seconds}</div>; } }