Component·续1

[!NOTE]

For many use cases, defining componentDidMount, componentDidUpdate, and componentWillUnmount together in class components is equivalent to calling useEffect in function components. In the rare cases where it's important for the code to run before browser paint, useLayoutEffect is a closer match.

See how to migrate.


forceUpdate(callback?)

Forces a component to re-render.

Usually, this is not necessary. If your component's render method only reads from this.props, this.state, or this.context, it will re-render automatically when you call setState inside your component or one of its parents. However, if your component's render method reads directly from an external data source, you have to tell React to update the user interface when that data source changes. That's what forceUpdate lets you do.

Try to avoid all uses of forceUpdate and only read from this.props and this.state in render.

Parameters

  • optional callback If specified, React will call the callback you've provided after the update is committed.

Returns

forceUpdate does not return anything.

Caveats

[!NOTE]

Reading an external data source and forcing class components to re-render in response to its changes with forceUpdate has been superseded by useSyncExternalStore in function components.


getSnapshotBeforeUpdate(prevProps, prevState)

If you implement getSnapshotBeforeUpdate, React will call it immediately before React updates the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle method will be passed as a parameter to componentDidUpdate.

For example, you can use it in a UI like a chat thread that needs to preserve its scroll position during updates:

```js {7-15,17} class ScrollingList extends React.Component { constructor(props) { super(props); this.listRef = React.createRef(); }

getSnapshotBeforeUpdate(prevProps, prevState) { // Are we adding new items to the list? // Capture the scroll position so we can adjust scroll later. if (prevProps.list.length < this.props.list.length) { const list = this.listRef.current; return list.scrollHeight - list.scrollTop; } return null; }

componentDidUpdate(prevProps, prevState, snapshot) { // If we have a snapshot value, we've just added new items. // Adjust scroll so these new items don't push the old ones out of view. // (snapshot here is the value returned from getSnapshotBeforeUpdate) if (snapshot !== null) { const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; } }

render() { return (

{/ ...contents... /}
); } }


In the above example, it is important to read the `scrollHeight` property directly in `getSnapshotBeforeUpdate`. It is not safe to read it in [`render`](#render), [`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops), or [`UNSAFE_componentWillUpdate`](#unsafe_componentwillupdate) because there is a potential time gap between these methods getting called and React updating the DOM.

#### 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.

#### Returns

You should return a snapshot value of any type that you'd like, or `null`. The value you returned will be passed as the third argument to [`componentDidUpdate`.](#componentdidupdate)

#### Caveats

- `getSnapshotBeforeUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`.

> [!NOTE]
>
> At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function components. This use case is very uncommon, but if you have the need for it, for now you'll have to write a class component.
>

---

### `render()`

The `render` method is the only required method in a class component.

The `render` method should specify what you want to appear on the screen, for example:

```js {4-6}
import { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

React may call render at any moment, so you shouldn't assume that it runs at a particular time. Usually, the render method should return a piece of JSX, but a few other return types (like strings) are supported. To calculate the returned JSX, the render method can read this.props, this.state, and this.context.

You should write the render method as a pure function, meaning that it should return the same result if props, state, and context are the same. It also shouldn't contain side effects (like setting up subscriptions) or interact with the browser APIs. Side effects should happen either in event handlers or methods like componentDidMount.

Parameters

render does not take any parameters.

Returns

render can return any valid React node. This includes React elements such as <div />, strings, numbers, portals, empty nodes (null, undefined, true, and false), and arrays of React nodes.

Caveats

  • render should be written as a pure function of props, state, and context. It should not have side effects.

  • render will not get called if shouldComponentUpdate is defined and returns false.

  • When Strict Mode is on, React will call render twice in development and then throw away one of the results. This helps you notice the accidental side effects that need to be moved out of the render method.

  • There is no one-to-one correspondence between the render call and the subsequent componentDidMount or componentDidUpdate call. Some of the render call results may be discarded by React when it's beneficial.


setState(nextState, callback?)

Call setState to update the state of your React component.

```js {8-10} class Form extends Component { state = { name: 'Taylor', };

handleNameChange = (e) => { const newName = e.target.value; this.setState({ name: newName }); }

render() { return ( <>

Hello, {this.state.name}.

</> ); } }


`setState` enqueues changes to the component state. It tells React that this component and its children need to re-render with the new state. This is the main way you'll update the user interface in response to interactions.

> [!WARNING]
>
> Calling `setState` **does not** change the current state in the already executing code:
>
```js {6}
function handleClick() {
  console.log(this.state.name); // "Taylor"
  this.setState({
    name: 'Robin'
  });
  console.log(this.state.name); // Still "Taylor"!
}

It only affects what this.state will return starting from the next render.

You can also pass a function to setState. It lets you update state based on the previous state:

```js {2-6} handleIncreaseAge = () => { this.setState(prevState => { return { age: prevState.age + 1 }; }); }


You don't have to do this, but it's handy if you want to update state multiple times during the same event.

#### Parameters

* `nextState`: Either an object or a function.
  * If you pass an object as `nextState`, it will be shallowly merged into `this.state`.
  * If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state and props as arguments, and should return the object to be shallowly merged into `this.state`. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state.

* **optional** `callback`: If specified, React will call the `callback` you've provided after the update is committed.

#### Returns

`setState` does not return anything.

#### Caveats

- Think of `setState` as a *request* rather than an immediate command to update the component. When multiple components update their state in response to an event, React will batch their updates and re-render them together in a single pass at the end of the event. In the rare case that you need to force a particular state update to be applied synchronously, you may wrap it in [`flushSync`,](/reference/react-dom/flushSync) but this may hurt performance.

- `setState` does not update `this.state` immediately. This makes reading `this.state` right after calling `setState` a potential pitfall. Instead, use [`componentDidUpdate`](#componentdidupdate) or the setState `callback` argument, either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, you can pass a function to `nextState` as described above.

> [!NOTE]
>
> Calling `setState` in class components is similar to calling a [`set` function](/reference/react/useState#setstate) in function components.
>
> [See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function)
>

---

### `shouldComponentUpdate(nextProps, nextState, nextContext)`

If you define `shouldComponentUpdate`, React will call it to determine whether a re-render can be skipped.

If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped.

```js {6-18}
class Rectangle extends Component {
  state = {
    isHovered: false
  };

shouldComponentUpdate(nextProps, nextState) {
    if (
      nextProps.position.x === this.props.position.x &&
      nextProps.position.y === this.props.position.y &&
      nextProps.size.width === this.props.size.width &&
      nextProps.size.height === this.props.size.height &&
      nextState.isHovered === this.state.isHovered
    ) {
      // Nothing has changed, so a re-render is unnecessary
      return false;
    }
    return true;
  }

// ...
}

React calls shouldComponentUpdate before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate is used.

Parameters

  • nextProps: The next props that the component is about to render with. Compare nextProps to this.props to determine what changed.
  • nextState: The next state that the component is about to render with. Compare nextState to this.state to determine what changed.
  • nextContext: The next context that the component is about to render with. Compare nextContext to this.context to determine what changed. Only available if you specify static contextType.

Returns

Return true if you want the component to re-render. That's the default behavior.

Return false to tell React that re-rendering can be skipped.

Caveats

  • This method only exists as a performance optimization. If your component breaks without it, fix that first.

  • Consider using PureComponent instead of writing shouldComponentUpdate by hand. PureComponent shallowly compares props and state, and reduces the chance that you'll skip a necessary update.

  • We do not recommend doing deep equality checks or using JSON.stringify in shouldComponentUpdate. It makes performance unpredictable and dependent on the data structure of every prop and state. In the best case, you risk introducing multi-second stalls to your application, and in the worst case you risk crashing it.

  • Returning false does not prevent child components from re-rendering when their state changes.

  • Returning false does not guarantee that the component will not re-render. React will use the return value as a hint but it may still choose to re-render your component if it makes sense to do for other reasons.

[!NOTE]

Optimizing class components with shouldComponentUpdate is similar to optimizing function components with memo. Function components also offer more granular optimization with useMemo.


UNSAFE_componentWillMount()

If you define UNSAFE_componentWillMount, React will call it immediately after the constructor. It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives:

  • To initialize state, declare state as a class field or set this.state inside the constructor.
  • If you need to run a side effect or set up a subscription, move that logic to componentDidMount instead.

See examples of migrating away from unsafe lifecycles.

Parameters

UNSAFE_componentWillMount does not take any parameters.

Returns

UNSAFE_componentWillMount should not return anything.

Caveats

  • UNSAFE_componentWillMount will not get called if the component implements static getDerivedStateFromProps or getSnapshotBeforeUpdate.

  • Despite its naming, UNSAFE_componentWillMount does not guarantee that the component will get mounted if your app uses modern React features like Suspense. 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. This is why this method is "unsafe". Code that relies on mounting (like adding a subscription) should go into componentDidMount.

  • UNSAFE_componentWillMount is the only lifecycle method that runs during server rendering. For all practical purposes, it is identical to constructor, so you should use the constructor for this type of logic instead.

[!NOTE]

Calling setState inside UNSAFE_componentWillMount in a class component to initialize state is equivalent to passing that state as the initial state to useState in a function component.


UNSAFE_componentWillReceiveProps(nextProps, nextContext)

If you define UNSAFE_componentWillReceiveProps, React will call it when the component receives new props. 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 changes, move that logic to componentDidUpdate instead.
  • If you need to avoid re-computing some data only when a prop changes, use a memoization helper instead.
  • If you need to "reset" some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.
  • If you need to "adjust" some state when a prop changes, check whether you can compute all the necessary information from props alone during rendering. If you can't, use static getDerivedStateFromProps instead.

See examples of migrating away from unsafe lifecycles.

Parameters

  • nextProps: The next props that the component is about to receive from its parent component. Compare nextProps to this.props to determine what changed.
  • nextContext: The next context that the component is about to receive from the closest provider. Compare nextContext to this.context to determine what changed. Only available if you specify static contextType.

Returns

UNSAFE_componentWillReceiveProps should not return anything.

Caveats