React.Component
:class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
React.Component
subclass is called [render()](<https://reactjs.org/docs/react-component.html#render>)
. All the other methods described on this page are optional.Note:React doesn’t force you to use the ES6 class syntax. If you prefer to avoid it, you may use the create-react-class module or a similar custom abstraction instead. Take a look at Using React without ES6 to learn more.
[constructor()](<https://reactjs.org/docs/react-component.html#constructor>)
[static getDerivedStateFromProps()](<https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops>)
[render()](<https://reactjs.org/docs/react-component.html#render>)
[componentDidMount()](<https://reactjs.org/docs/react-component.html#componentdidmount>)
Note:These methods are considered legacy and you should avoid them in new code:UNSAFE_componentWillMount()
[static getDerivedStateFromProps()](<https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops>)
[shouldComponentUpdate()](<https://reactjs.org/docs/react-component.html#shouldcomponentupdate>)
[render()](<https://reactjs.org/docs/react-component.html#render>)
[getSnapshotBeforeUpdate()](<https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate>)
[componentDidUpdate()](<https://reactjs.org/docs/react-component.html#componentdidupdate>)
Note:These methods are considered legacy and you should avoid them in new code:UNSAFE_componentWillUpdate()UNSAFE_componentWillReceiveProps()
[componentWillUnmount()](<https://reactjs.org/docs/react-component.html#componentwillunmount>)
[static getDerivedStateFromError()](<https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror>)
[componentDidCatch()](<https://reactjs.org/docs/react-component.html#componentdidcatch>)
[setState()](<https://reactjs.org/docs/react-component.html#setstate>)
[forceUpdate()](<https://reactjs.org/docs/react-component.html#forceupdate>)
[defaultProps](<https://reactjs.org/docs/react-component.html#defaultprops>)
[displayName](<https://reactjs.org/docs/react-component.html#displayname>)
[props](<https://reactjs.org/docs/react-component.html#props>)
[state](<https://reactjs.org/docs/react-component.html#state>)
render()
render()
render()
method is the only required method in a class component.this.props
and this.state
and return one of the following types:<div />
and <MyComponent />
are React elements that instruct React to render a DOM node, or another user-defined component, respectively.null
. Render nothing. (Mostly exists to support return test && <Child />
pattern, where test
is boolean.)render()
function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.componentDidMount()
or the other lifecycle methods instead. Keeping render()
pure makes components easier to think about.Noterender() will not be invoked if shouldComponentUpdate() returns false.
constructor()
constructor(props)
React.Component
subclass, you should call super(props)
before any other statement. Otherwise, this.props
will be undefined in the constructor, which can lead to bugs.setState()
in the constructor()
. Instead, if your component needs to use local state, assign the initial state to this.state
directly in the constructor:constructor(props) { super(props); // Don't call this.setState() here! this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); }
this.state
directly. In all other methods, you need to use this.setState()
instead.componentDidMount()
instead.NoteAvoid copying props into state! This is a common mistake:constructor(props) { super(props); // Don't do this! this.state = { color: props.color }; }The problem is that it’s both unnecessary (you can use this.props.color directly instead), and creates bugs (updates to the color prop won’t be reflected in the state).Only use this pattern if you intentionally want to ignore prop updates. In that case, it makes sense to rename the prop to be called initialColor or defaultColor. You can then force a component to “reset” its internal state by changing its key when necessary.Read our blog post on avoiding derived state to learn about what to do if you think you need some state to depend on the props.
componentDidMount()
componentDidMount()
componentDidMount()
is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.componentWillUnmount()
.setState()
immediately in componentDidMount()
. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render()
will 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 the constructor()
instead. 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.componentDidUpdate()
componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate()
is invoked immediately after updating occurs. This method is not called for the initial render.componentDidUpdate(prevProps) { // Typical usage (don't forget to compare props): if (this.props.userID !== prevProps.userID) { this.fetchData(this.props.userID); } }
setState()
immediately in componentDidUpdate()
but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you’re trying to “mirror” some state to a prop coming from above, consider using the prop directly instead. Read more about why copying props into state causes bugs.getSnapshotBeforeUpdate()
lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate()
. Otherwise this parameter will be undefined.NotecomponentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.
componentWillUnmount()
componentWillUnmount()
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount()
.setState()
in componentWillUnmount()
because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState)
shouldComponentUpdate()
to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.shouldComponentUpdate()
is invoked 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.[PureComponent](<https://reactjs.org/docs/react-api.html#reactpurecomponent>)
instead of writing shouldComponentUpdate()
by hand. PureComponent
performs a shallow comparison of props and state, and reduces the chance that you’ll skip a necessary update.this.props
with nextProps
and this.state
with nextState
and return false
to tell React the update can be skipped. Note that returning false
does not prevent child components from re-rendering when their state changes.JSON.stringify()
in shouldComponentUpdate()
. It is very inefficient and will harm performance.shouldComponentUpdate()
returns false
, then [UNSAFE_componentWillUpdate()](<https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate>)
, [render()](<https://reactjs.org/docs/react-component.html#render>)
, and [componentDidUpdate()](<https://reactjs.org/docs/react-component.html#componentdidupdate>)
will not be invoked. In the future React may treat shouldComponentUpdate()
as a hint rather than a strict directive, and returning false
may still result in a re-rendering of the component.static getDerivedStateFromProps()
static getDerivedStateFromProps(props, state)
getDerivedStateFromProps
is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null
to update nothing.<Transition>
component that compares its previous and next children to decide which of them to animate in and out.[componentDidUpdate](<https://reactjs.org/docs/react-component.html#componentdidupdate>)
lifecycle instead.key
instead.getDerivedStateFromProps()
and the other class methods by extracting pure functions of the component props and state outside the class definition.UNSAFE_componentWillReceiveProps
, which only fires when the parent causes a re-render and not as a result of a local setState
.getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate(prevProps, prevState)
getSnapshotBeforeUpdate()
is invoked right before the most recently rendered output is committed to e.g. 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()
.null
) should be returned.scrollHeight
property in getSnapshotBeforeUpdate
because there may be delays between “render” phase lifecycles (like render
) and “commit” phase lifecycles (like getSnapshotBeforeUpdate
and componentDidUpdate
).static getDerivedStateFromError()
or componentDidCatch()
. Updating state from these lifecycles lets you capture an unhandled JavaScript error in the below tree and display a fallback UI.NoteError boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.
static getDerivedStateFromError()
static getDerivedStateFromError(error)
NotegetDerivedStateFromError() is called during the “render” phase, so side-effects are not permitted. For those use cases, use componentDidCatch() instead.
componentDidCatch()
componentDidCatch(error, info)
error
- The error that was thrown.info
- An object with a componentStack
key containing information about which component threw the error.componentDidCatch()
is called during the “commit” phase, so side-effects are permitted. It should be used for things like logging errors:componentDidCatch()
handles errors.window
, this means that any window.onerror
or window.addEventListener('error', callback)
will intercept the errors that have been caught by componentDidCatch()
.componentDidCatch()
.NoteIn the event of an error, you can render a fallback UI with componentDidCatch() by calling setState, but this will be deprecated in a future release. Use static getDerivedStateFromError() to handle fallback rendering instead.
UNSAFE_componentWillMount()
UNSAFE_componentWillMount()
NoteThis lifecycle was previously named componentWillMount. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
UNSAFE_componentWillMount()
is invoked just before mounting occurs. It is called before render()
, therefore calling setState()
synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor()
instead for initializing state.componentDidMount()
instead.UNSAFE_componentWillReceiveProps()
UNSAFE_componentWillReceiveProps(nextProps)
NoteThis lifecycle was previously named componentWillReceiveProps. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
Note:Using this lifecycle method often leads to bugs and inconsistenciesIf you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.If you used componentWillReceiveProps to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.For other use cases, follow the recommendations in this blog post about derived state.
UNSAFE_componentWillReceiveProps()
is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props
and nextProps
and perform state transitions using this.setState()
in this method.UNSAFE_componentWillReceiveProps()
with initial props during mounting. It only calls this method if some of component’s props may update. Calling this.setState()
generally doesn’t trigger UNSAFE_componentWillReceiveProps()
.UNSAFE_componentWillUpdate()
UNSAFE_componentWillUpdate(nextProps, nextState)
NoteThis lifecycle was previously named componentWillUpdate. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
UNSAFE_componentWillUpdate()
is invoked just before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.this.setState()
here; nor should you do anything else (e.g. dispatch a Redux action) that would trigger an update to a React component before UNSAFE_componentWillUpdate()
returns.componentDidUpdate()
. If you were reading from the DOM in this method (e.g. to save a scroll position), you can move that logic to getSnapshotBeforeUpdate()
.NoteUNSAFE_componentWillUpdate() will not be invoked if shouldComponentUpdate() returns false.
setState()
and forceUpdate()
.setState()
setState(updater, [callback])
setState()
enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.setState()
as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.setState()
does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state
right after calling setState()
a potential pitfall. Instead, use componentDidUpdate
or a setState
callback (setState(updater, callback)
), 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, read about the updater
argument below.setState()
will always lead to a re-render unless shouldComponentUpdate()
returns false
. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate()
, calling setState()
only when the new state differs from the previous state will avoid unnecessary re-renders.updater
function with the signature:(state, props) => stateChange
state
is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state
and props
. For instance, suppose we wanted to increment a value in state by props.step
:this.setState((state, props) => { return {counter: state.counter + props.step}; });
state
and props
received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state
.setState()
is an optional callback function that will be executed once setState
is completed and the component is re-rendered. Generally we recommend using componentDidUpdate()
for such logic instead.setState()
instead of a function:setState(stateChange[, callback])
stateChange
into the new state, e.g., to adjust a shopping cart item quantity:this.setState({quantity: 2})
setState()
is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:Object.assign( previousState, {quantity: state.quantity + 1}, {quantity: state.quantity + 1}, ... )
this.setState((state) => { return {quantity: state.quantity + 1}; });
forceUpdate()
component.forceUpdate(callback)
render()
method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate()
.forceUpdate()
will cause render()
to be called on the component, skipping shouldComponentUpdate()
. This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate()
method of each child. React will still only update the DOM if the markup changes.forceUpdate()
and only read from this.props
and this.state
in render()
.defaultProps
defaultProps
can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined
props, but not for null
props. For example:props.color
is not provided, it will be set by default to 'blue'
:render() { return <CustomButton /> ; // props.color will be set to blue }
props.color
is set to null
, it will remain null
:render() { return <CustomButton color={null} /> ; // props.color will remain null }
displayName
displayName
string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see Wrap the Display Name for Easy Debugging for details.props
this.props
contains the props that were defined by the caller of this component. See Components and Props for an introduction to props.this.props.children
is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself.state
this.state
directly, as calling setState()
afterwards may replace the mutation you made. Treat this.state
as if it were immutable.