Component
[!WARNING]
We recommend defining components as functions instead of classes. See how to migrate.
Component is the base class for the React components defined as JavaScript classes. Class components are still supported by React, but we don't recommend using them in new code.
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Reference
Component
To define a React component as a class, extend the built-in Component class and define a render method:
import { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Only the render method is required, other methods are optional.
context
The context of a class component is available as this.context. It is only available if you specify which context you want to receive using static contextType.
A class component can only read one context at a time.
```js {2,5} class Button extends Component { static contextType = ThemeContext;
render() { const theme = this.context; const className = 'button-' + theme; return ( ); } }
> [!NOTE]
>
> Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components.
>
> [See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function)
>
---
### `props`
The props passed to a class component are available as `this.props`.
```js {3}
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
<Greeting name="Taylor" />
[!NOTE]
Reading
this.propsin class components is equivalent to declaring props in function components.
state
The state of a class component is available as this.state. The state field must be an object. Do not mutate the state directly. If you wish to change the state, call setState with the new state.
```js {2-4,7-9,18} class Counter extends Component { state = { age: 42, };
handleAgeChange = () => { this.setState({ age: this.state.age + 1 }); };
render() { return ( <>
You are {this.state.age}.
</> ); } }
> [!NOTE]
>
> Defining `state` in class components is equivalent to calling [`useState`](/reference/react/useState) in function components.
>
> [See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function)
>
---
### `constructor(props)`
The [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) runs before your class component *mounts* (gets added to the screen). Typically, a constructor is only used for two purposes in React. It lets you declare state and [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) your class methods to the class instance:
```js {2-6}
class Counter extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// ...
}
If you use modern JavaScript syntax, constructors are rarely needed. Instead, you can rewrite this code above using the public class field syntax which is supported both by modern browsers and tools like Babel:
```js {2,4} class Counter extends Component { state = { counter: 0 };
handleClick = () => { // ... }
A constructor should not contain any side effects or subscriptions.
#### Parameters
* `props`: The component's initial props.
#### Returns
`constructor` should not return anything.
#### Caveats
* Do not run any side effects or subscriptions in the constructor. Instead, use [`componentDidMount`](#componentdidmount) for that.
* Inside a constructor, you need to call `super(props)` before any other statement. If you don't do that, `this.props` will be `undefined` while the constructor runs, which can be confusing and cause bugs.
* Constructor is the only place where you can assign [`this.state`](#state) directly. In all other methods, you need to use [`this.setState()`](#setstate) instead. Do not call `setState` in the constructor.
* When you use [server rendering,](/reference/react-dom/server) the constructor will run on the server too, followed by the [`render`](#render) method. However, lifecycle methods like `componentDidMount` or `componentWillUnmount` will not run on the server.
* When [Strict Mode](/reference/react/StrictMode) is on, React will call `constructor` twice in development and then throw away one of the instances. This helps you notice the accidental side effects that need to be moved out of the `constructor`.
> [!NOTE]
>
> There is no exact equivalent for `constructor` in function components. To declare state in a function component, call [`useState`.](/reference/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state)
>
---
### `componentDidCatch(error, info)`
If you define `componentDidCatch`, React will call it when some child component (including distant children) throws an error during rendering. This lets you log that error to an error reporting service in production.
Typically, it is used together with [`static getDerivedStateFromError`](#static-getderivedstatefromerror) which lets you update state in response to an error and display an error message to the user. A component with these methods is called an *Error Boundary*.
[See an example.](#catching-rendering-errors-with-an-error-boundary)
#### Parameters
* `error`: The error that was thrown. In practice, it will usually be an instance of [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) but this is not guaranteed because JavaScript allows to [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) any value, including strings or even `null`.
* `info`: An object containing additional information about the error. Its `componentStack` field contains a stack trace with the component that threw, as well as the names and source locations of all its parent components. In production, the component names will be minified. If you set up production error reporting, you can decode the component stack using sourcemaps the same way as you would do for regular JavaScript error stacks.
#### Returns
`componentDidCatch` should not return anything.
#### Caveats
* In the past, it was common to call `setState` inside `componentDidCatch` in order to update the UI and display the fallback error message. This is deprecated in favor of defining [`static getDerivedStateFromError`.](#static-getderivedstatefromerror)
* Production and development builds of React slightly differ in the way `componentDidCatch` handles errors. In development, the errors will bubble up to `window`, which means that any `window.onerror` or `window.addEventListener('error', callback)` will intercept the errors that have been caught by `componentDidCatch`. In production, instead, the errors will not bubble up, which means any ancestor error handler will only receive errors not explicitly caught by `componentDidCatch`.
> [!NOTE]
>
> There is no direct equivalent for `componentDidCatch` in function components yet. If you'd like to avoid creating class components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, you can use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that for you.
>
---
### `componentDidMount()`
If you define the `componentDidMount` method, React will call it when your component is added *(mounted)* to the screen. This is a common place to start data fetching, set up subscriptions, or manipulate the DOM nodes.
If you implement `componentDidMount`, you usually need to implement other lifecycle methods to avoid bugs. For example, if `componentDidMount` reads some state or props, you also have to implement [`componentDidUpdate`](#componentdidupdate) to handle their changes, and [`componentWillUnmount`](#componentwillunmount) to clean up whatever `componentDidMount` was doing.
```js {6-8}
class ChatRoom extends Component {
state = {
serverUrl: 'https://localhost:1234'
};
componentDidMount() {
this.setupConnection();
}
componentDidUpdate(prevProps, prevState) {
if (
this.props.roomId !== prevProps.roomId ||
this.state.serverUrl !== prevState.serverUrl
) {
this.destroyConnection();
this.setupConnection();
}
}
componentWillUnmount() {
this.destroyConnection();
}
// ...
}
Parameters
componentDidMount does not take any parameters.
Returns
componentDidMount should not return anything.
Caveats
-
When Strict Mode is on, in development React will call
componentDidMount, then immediately callcomponentWillUnmount, and then callcomponentDidMountagain. This helps you notice if you forgot to implementcomponentWillUnmountor if its logic doesn't fully "mirror" whatcomponentDidMountdoes. -
Although you may call
setStateimmediately incomponentDidMount, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though therenderwill be called twice in this case, the user won't see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in theconstructorinstead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.
[!NOTE]
For many use cases, defining
componentDidMount,componentDidUpdate, andcomponentWillUnmounttogether in class components is equivalent to callinguseEffectin function components. In the rare cases where it's important for the code to run before browser paint,useLayoutEffectis a closer match.
componentDidUpdate(prevProps, prevState, snapshot?)
If you define the componentDidUpdate method, React will call it immediately after your component has been re-rendered with updated props or state. This method is not called for the initial render.
You can use it to manipulate the DOM after an update. This is also a common place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). Typically, you'd use it together with componentDidMount and componentWillUnmount:
```js {10-18} class ChatRoom extends Component { state = { serverUrl: 'https://localhost:1234' };
componentDidMount() { this.setupConnection(); }
componentDidUpdate(prevProps, prevState) { if ( this.props.roomId !== prevProps.roomId || this.state.serverUrl !== prevState.serverUrl ) { this.destroyConnection(); this.setupConnection(); } }
componentWillUnmount() { this.destroyConnection(); }
// ... }
[See more examples.](#adding-lifecycle-methods-to-a-class-component)
#### Parameters
* `prevProps`: Props before the update. Compare `prevProps` to [`this.props`](#props) to determine what changed.
* `prevState`: State before the update. Compare `prevState` to [`this.state`](#state) to determine what changed.
* `snapshot`: If you implemented [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate), `snapshot` will contain the value you returned from that method. Otherwise, it will be `undefined`.
#### Returns
`componentDidUpdate` should not return anything.
#### Caveats
- `componentDidUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`.
- The logic inside `componentDidUpdate` should usually be wrapped in conditions comparing `this.props` with `prevProps`, and `this.state` with `prevState`. Otherwise, there's a risk of creating infinite loops.
- Although you may call [`setState`](#setstate) immediately in `componentDidUpdate`, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the [`render`](#render) will be called twice in this case, the user won't see the intermediate state. This pattern often causes performance issues, but it may be necessary for rare cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.
> [!NOTE]
>
> For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match.
>
> [See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function)
>
---
### `componentWillMount()`
> [!WARNING]
>
> This API has been renamed from `componentWillMount` to [`UNSAFE_componentWillMount`.](#unsafe_componentwillmount) The old name has been deprecated. In a future major version of React, only the new name will work.
>
> Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components.
>
---
### `componentWillReceiveProps(nextProps)`
> [!WARNING]
>
> This API has been renamed from `componentWillReceiveProps` to [`UNSAFE_componentWillReceiveProps`.](#unsafe_componentwillreceiveprops) The old name has been deprecated. In a future major version of React, only the new name will work.
>
> Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components.
>
---
### `componentWillUpdate(nextProps, nextState)`
> [!WARNING]
>
> This API has been renamed from `componentWillUpdate` to [`UNSAFE_componentWillUpdate`.](#unsafe_componentwillupdate) The old name has been deprecated. In a future major version of React, only the new name will work.
>
> Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components.
>
---
### `componentWillUnmount()`
If you define the `componentWillUnmount` method, React will call it before your component is removed *(unmounted)* from the screen. This is a common place to cancel data fetching or remove subscriptions.
The logic inside `componentWillUnmount` should "mirror" the logic inside [`componentDidMount`.](#componentdidmount) For example, if `componentDidMount` sets up a subscription, `componentWillUnmount` should clean up that subscription. If the cleanup logic in your `componentWillUnmount` reads some props or state, you will usually also need to implement [`componentDidUpdate`](#componentdidupdate) to clean up resources (such as subscriptions) corresponding to the old props and state.
```js {20-22}
class ChatRoom extends Component {
state = {
serverUrl: 'https://localhost:1234'
};
componentDidMount() {
this.setupConnection();
}
componentDidUpdate(prevProps, prevState) {
if (
this.props.roomId !== prevProps.roomId ||
this.state.serverUrl !== prevState.serverUrl
) {
this.destroyConnection();
this.setupConnection();
}
}
componentWillUnmount() {
this.destroyConnection();
}
// ...
}
Parameters
componentWillUnmount does not take any parameters.
Returns
componentWillUnmount should not return anything.
Caveats
- When Strict Mode is on, in development React will call
componentDidMount, then immediately callcomponentWillUnmount, and then callcomponentDidMountagain. This helps you notice if you forgot to implementcomponentWillUnmountor if its logic doesn't fully "mirror" whatcomponentDidMountdoes.
