Component·续2
-
Despite its naming,
UNSAFE_componentWillReceivePropsdoes not guarantee that the component will receive those props if your app uses modern React features likeSuspense. If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go intocomponentDidUpdate. -
UNSAFE_componentWillReceivePropsdoes not mean that the component has received different props than the last time. You need to comparenextPropsandthis.propsyourself to check if something changed. -
React doesn't call
UNSAFE_componentWillReceivePropswith initial props during mounting. It only calls this method if some of component's props are going to be updated. For example, callingsetStatedoesn't generally triggerUNSAFE_componentWillReceivePropsinside the same component.
[!NOTE]
Calling
setStateinsideUNSAFE_componentWillReceivePropsin a class component to "adjust" state is equivalent to calling thesetfunction fromuseStateduring rendering in a function component.
UNSAFE_componentWillUpdate(nextProps, nextState)
If you define UNSAFE_componentWillUpdate, React will call it before rendering with the new props or state. It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives:
- If you need to run a side effect (for example, fetch data, run an animation, or reinitialize a subscription) in response to prop or state changes, move that logic to
componentDidUpdateinstead. - If you need to read some information from the DOM (for example, to save the current scroll position) so that you can use it in
componentDidUpdatelater, read it insidegetSnapshotBeforeUpdateinstead.
See examples of migrating away from unsafe lifecycles.
Parameters
nextProps: The next props that the component is about to render with. ComparenextPropstothis.propsto determine what changed.nextState: The next state that the component is about to render with. ComparenextStatetothis.stateto determine what changed.
Returns
UNSAFE_componentWillUpdate should not return anything.
Caveats
-
UNSAFE_componentWillUpdatewill not get called ifshouldComponentUpdateis defined and returnsfalse. -
UNSAFE_componentWillUpdatewill not get called if the component implementsstatic getDerivedStateFromPropsorgetSnapshotBeforeUpdate. -
It's not supported to call
setState(or any method that leads tosetStatebeing called, like dispatching a Redux action) duringcomponentWillUpdate. -
Despite its naming,
UNSAFE_componentWillUpdatedoes not guarantee that the component will update if your app uses modern React features likeSuspense. If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props and state might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go intocomponentDidUpdate. -
UNSAFE_componentWillUpdatedoes not mean that the component has received different props or state than the last time. You need to comparenextPropswiththis.propsandnextStatewiththis.stateyourself to check if something changed. -
React doesn't call
UNSAFE_componentWillUpdatewith initial props and state during mounting.
[!NOTE]
There is no direct equivalent to
UNSAFE_componentWillUpdatein function components.
static contextType
If you want to read this.context from your class component, you must specify which context it needs to read. The context you specify as the static contextType must be a value previously created by createContext.
```js {2} 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)
>
---
### `static defaultProps`
You can define `static defaultProps` to set the default props for the class. They will be used for `undefined` and missing props, but not for `null` props.
For example, here is how you define that the `color` prop should default to `'blue'`:
```js {2-4}
class Button extends Component {
static defaultProps = {
color: 'blue'
};
render() {
return <button className={this.props.color}>click me</button>;
}
}
If the color prop is not provided or is undefined, it will be set by default to 'blue':
<>
{/* this.props.color is "blue" */}
<Button />
{/* this.props.color is "blue" */}
<Button color={undefined} />
{/* this.props.color is null */}
<Button color={null} />
{/* this.props.color is "red" */}
<Button color="red" />
</>
[!NOTE]
Defining
defaultPropsin class components is similar to using default values in function components.
static getDerivedStateFromError(error)
If you define static getDerivedStateFromError, React will call it when a child component (including distant children) throws an error during rendering. This lets you display an error message instead of clearing the UI.
Typically, it is used together with componentDidCatch which lets you send the error report to some analytics service. A component with these methods is called an Error Boundary.
Parameters
error: The error that was thrown. In practice, it will usually be an instance ofErrorbut this is not guaranteed because JavaScript allows tothrowany value, including strings or evennull.
Returns
static getDerivedStateFromError should return the state telling the component to display the error message.
Caveats
static getDerivedStateFromErrorshould be a pure function. If you want to perform a side effect (for example, to call an analytics service), you need to also implementcomponentDidCatch.
[!NOTE]
There is no direct equivalent for
static getDerivedStateFromErrorin function components yet. If you'd like to avoid creating class components, write a singleErrorBoundarycomponent like above and use it throughout your app. Alternatively, use thereact-error-boundarypackage which does that.
static getDerivedStateFromProps(props, state)
If you define static getDerivedStateFromProps, React will call it right before calling render, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
This method exists for rare use cases where the state depends on changes in props over time. For example, this Form component resets the email state when the userID prop changes:
```js {7-18} class Form extends Component { state = { email: this.props.defaultEmail, prevUserID: this.props.userID };
static getDerivedStateFromProps(props, state) { // Any time the current user changes, // Reset any parts of state that are tied to that user. // In this simple example, that's just the email. if (props.userID !== state.prevUserID) { return { prevUserID: props.userID, email: props.defaultEmail }; } return null; }
// ... }
Note that this pattern requires you to keep a previous value of the prop (like `userID`) in state (like `prevUserID`).
> [!WARNING]
>
> Deriving state leads to verbose code and makes your components difficult to think about. [Make sure you're familiar with simpler alternatives:](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html)
>
> - If you need to **perform a side effect** (for example, data fetching or an animation) in response to a change in props, use [`componentDidUpdate`](#componentdidupdate) method instead.
> - If you want to **re-compute some data only when a prop changes,** [use a memoization helper instead.](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization)
> - If you want to **"reset" some state when a prop changes,** consider either making a component [fully controlled](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a key](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead.
>
#### Parameters
- `props`: The next props that the component is about to render with.
- `state`: The next state that the component is about to render with.
#### Returns
`static getDerivedStateFromProps` return an object to update the state, or `null` to update nothing.
#### Caveats
- This method is fired on *every* render, regardless of the cause. This is different from [`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops), which only fires when the parent causes a re-render and not as a result of a local `setState`.
- This method doesn't have access to the component instance. If you'd like, you can reuse some code between `static getDerivedStateFromProps` and the other class methods by extracting pure functions of the component props and state outside the class definition.
> [!NOTE]
>
> Implementing `static getDerivedStateFromProps` in a class component is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component.
>
---
## Usage
### Defining a class component
To define a React component as a class, extend the built-in `Component` class and define a [`render` method:](#render)
```js
import { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
React will call your render method whenever it needs to figure out what to display on the screen. Usually, you will return some JSX from it. Your render method should be a pure function: it should only calculate the JSX.
Similarly to function components, a class component can receive information by props from its parent component. However, the syntax for reading props is different. For example, if the parent component renders <Greeting name="Taylor" />, then you can read the name prop from this.props, like this.props.name:
import { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default function App() {
return (
<>
<Greeting name="Sara" />
<Greeting name="Cahal" />
<Greeting name="Edite" />
</>
);
}
Note that Hooks (functions starting with use, like useState) are not supported inside class components.
[!WARNING]
We recommend defining components as functions instead of classes. See how to migrate.
Adding state to a class component
To add state to a class, assign an object to a property called state. To update state, call this.setState.
import { Component } from 'react';
export default class Counter extends Component {
state = {
name: 'Taylor',
age: 42,
};
handleNameChange = (e) => {
this.setState({
name: e.target.value
});
}
handleAgeChange = () => {
this.setState({
age: this.state.age + 1
});
};
render() {
return (
<>
<input
value={this.state.name}
onChange={this.handleNameChange}
/>
<button onClick={this.handleAgeChange}>
Increment age
</button>
<p>Hello, {this.state.name}. You are {this.state.age}.</p>
</>
);
}
}
button { display: block; margin-top: 10px; }
[!WARNING]
We recommend defining components as functions instead of classes. See how to migrate.
Adding lifecycle methods to a class component
There are a few special methods you can define on your class.
If you define the componentDidMount method, React will call it when your component is added (mounted) to the screen. React will call componentDidUpdate after your component re-renders due to changed props or state. React will call componentWillUnmount after your component has been removed (unmounted) from the screen.
If you implement componentDidMount, you usually need to implement all three lifecycles to avoid bugs. For example, if componentDidMount reads some state or props, you also have to implement componentDidUpdate to handle their changes, and componentWillUnmount to clean up whatever componentDidMount was doing.
For example, this ChatRoom component keeps a chat connection synchronized with props and state:
```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js';
export default function App() { const [roomId, setRoomId] = useState('general'); const [show, setShow] = useState(false); return ( <> {show &&
} {show &&
```js src/ChatRoom.js active
import { Component } from 'react';
import { createConnection } from './chat.js';
export default 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();
}
setupConnection() {
this.connection = createConnection(
this.state.serverUrl,
this.props.roomId
);
this.connection.connect();
}
destroyConnection() {
this.connection.disconnect();
this.connection = null;
}
render() {
return (
<>
<label>
Server URL:{' '}
<input
value={this.state.serverUrl}
onChange={e => {
this.setState({
serverUrl: e.target.value
});
}}
/>
</label>
<h1>Welcome to the {this.props.roomId} room!</h1>
</>
);
}
}
js src/chat.js
export function createConnection(serverUrl, roomId) {
// A real implementation would actually connect to the server
return {
connect() {
console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...');
},
disconnect() {
console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl);
}
};
}
