StrictMode
is a tool for highlighting potential problems in an application. Like
Fragment
,
StrictMode
does not render any visible UI. It activates additional checks and warnings for its descendants.
Note:
Strict mode checks are run in development mode only;
they do not impact the production build
.
You can enable strict mode for any part of your application. For example:
In the above example, strict mode checks will
not
be run against the
Header
and
Footer
components. However,
ComponentOne
and
ComponentTwo
, as well as all of their descendants, will have the checks.
Additional functionality will be added with future releases of React.
Identifying unsafe lifecycles
As explained in this blog post, certain legacy lifecycle methods are unsafe for use in async React applications. However, if your application uses third party libraries, it can be difficult to ensure that these lifecycles aren’t being used. Fortunately, strict mode can help with this!
When strict mode is enabled, React compiles a list of all class components using the unsafe lifecycles, and logs a warning message with information about these components, like so:
Addressing the issues identified by strict mode
now
will make it easier for you to take advantage of concurrent rendering in future releases of React.
Warning about legacy string ref API usage
Previously, React provided two ways for managing refs: the legacy string ref API and the callback API. Although the string ref API was the more convenient of the two, it had several downsides and so our official recommendation was to use the callback form instead.
React 16.3 added a third option that offers the convenience of a string ref without any of the downsides:
Since object refs were largely added as a replacement for string refs, strict mode now warns about usage of string refs.
Note:
Callback refs will continue to be supported in addition to the new
createRef
API.
You don’t need to replace callback refs in your components. They are slightly more flexible, so they will remain as an advanced feature.
Learn more about the new
createRef
API here.
Warning about deprecated findDOMNode usage
React used to support
findDOMNode
to search the tree for a DOM node given a class instance. Normally you don’t need this because you can attach a ref directly to a DOM node.
findDOMNode
can also be used on class components but this was breaking abstraction levels by allowing a parent to demand that certain children were rendered. It creates a refactoring hazard where you can’t change the implementation details of a component because a parent might be reaching into its DOM node.
findDOMNode
only returns the first child, but with the use of Fragments, it is possible for a component to render multiple DOM nodes.
findDOMNode
is a one time read API. It only gave you an answer when you asked for it. If a child component renders a different node, there is no way to handle this change. Therefore
findDOMNode
only worked if components always return a single DOM node that never changes.
You can instead make this explicit by passing a ref to your custom component and pass that along to the DOM using ref forwarding.
You can also add a wrapper DOM node in your component and attach a ref directly to it.
In CSS, the
display: contents
attribute can be used if you don’t want the node to be part of the layout.
Detecting unexpected side effects
Conceptually, React does work in two phases:
The
render
phase determines what changes need to be made to e.g. the DOM. During this phase, React calls
render
and then compares the result to the previous render.
The
commit
phase is when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like
componentDidMount
and
componentDidUpdate
during this phase.
The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming concurrent mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption).
Render phase lifecycles include the following class component methods:
Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be non-deterministic.
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
Class component
constructor
,
render
, and
shouldComponentUpdate
methods
Class component static
getDerivedStateFromProps
method
Function component bodies
State updater functions (the first argument to
setState
)
Functions passed to
useState
,
useMemo
, or
useReducer
Note:
This only applies to development mode.
Lifecycles will not be double-invoked in production mode.
At first glance, this code might not seem problematic. But if
SharedApplicationState.recordEvent
is not idempotent, then instantiating this component multiple times could lead to invalid application state. This sort of subtle bug might not manifest during development, or it might do so inconsistently and so be overlooked.
By intentionally double-invoking methods like the component constructor, strict mode makes patterns like this easier to spot.
Note:
In React 17, React automatically modifies the console methods like
console.log()
to silence the logs in the second call to lifecycle functions. However, it may cause undesired behavior in certain cases where a workaround can be used.
Starting from React 18, React does not suppress any logs. However, if you have React DevTools installed, the logs from the second call will appear slightly dimmed. React DevTools also offers a setting (off by default) to suppress them completely.
Detecting legacy context API
The legacy context API is error-prone, and will be removed in a future major version. It still works for all 16.x releases but will show this warning message in strict mode:
Read the new context API documentation to help migrate to the new version.
Ensuring reusable state
In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React will support remounting trees using the same component state used before unmounting.
This feature will give React better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects do not properly clean up subscriptions in the destroy callback, or implicitly assume they are only mounted or destroyed once.
To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.
To demonstrate the development behavior you’ll see in Strict Mode with this feature, consider what happens when React mounts a new component. Without this change, when a component mounts, React creates the effects:
* React mounts the component. * Layout effects are created. * Effects are created.
With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component:
* React mounts the component. * Layout effects are created. * Effect effects are created. * React simulates effects being destroyed on a mounted component. * Layout effects are destroyed. * Effects are destroyed. * React simulates effects being re-created on a mounted component. * Layout effects are created * Effect setup code runs
On the second mount, React will restore the state from the first mount. This feature simulates user behavior such as a user tabbing away from a screen and back, ensuring that code will properly handle state restoration.
When the component unmounts, effects are destroyed as normal:
* React unmounts the component. * Layout effects are destroyed. * Effect effects are destroyed.
Unmounting and remounting includes:
componentDidMount
componentWillUnmount
useEffect
useLayoutEffect
useInsertionEffect
Note:
This only applies to development mode,
production behavior is unchanged
.
We provide a codemod script to automate the conversion.
As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don’t use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special
propTypes
property:
In this example, we are using a class component, but the same functionality could also be applied to function components, or components created by
React.memo
or
React.forwardRef
.
PropTypes
exports a range of validators that can be used to make sure the data you receive is valid. In this example, we’re using
PropTypes.string
. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons,
propTypes
is only checked in development mode.
PropTypes
Here is an example documenting the different validators provided:
import PropTypes from'prop-types';
MyComponent.propTypes ={ // You can declare that a prop is a specific JS type. By default, these // are all optional. optionalArray: PropTypes.array, optionalBool: PropTypes.bool, optionalFunc: PropTypes.func, optionalNumber: PropTypes.number, optionalObject: PropTypes.object, optionalString: PropTypes.string, optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: PropTypes.node,
// A React element. optionalElement: PropTypes.element,
// A React element type (ie. MyComponent). optionalElementType: PropTypes.elementType,
// You can also declare that a prop is an instance of a class. This uses // JS's instanceof operator. optionalMessage: PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating // it as an enum. optionalEnum: PropTypes.oneOf(['News','Photos']),
// An object that could be one of many types optionalUnion: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message) ]),
// An array of a certain type optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// An object with property values of a certain type optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// An object taking on a particular shape optionalObjectWithShape: PropTypes.shape({ color: PropTypes.string, fontSize: PropTypes.number }),
// An object with warnings on extra properties optionalObjectWithStrictShape: PropTypes.exact({ name: PropTypes.string, quantity: PropTypes.number }),
// You can chain any of the above with `isRequired` to make sure a warning // is shown if the prop isn't provided. requiredFunc: PropTypes.func.isRequired,
// A required value of any data type requiredAny: PropTypes.any.isRequired,
// You can also specify a custom validator. It should return an Error // object if the validation fails. Don't `console.warn` or throw, as this // won't work inside `oneOfType`. customProp:function(props, propName, componentName){ if(!/matchme/.test(props[propName])){ returnnewError( 'Invalid prop `'+ propName +'` supplied to'+ ' `'+ componentName +'`. Validation failed.' ); } },
// You can also supply a custom validator to `arrayOf` and `objectOf`. // It should return an Error object if the validation fails. The validator // will be called for each key in the array or object. The first two // arguments of the validator are the array or object itself, and the // current item's key. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName){ if(!/matchme/.test(propValue[key])){ returnnewError( 'Invalid prop `'+ propFullName +'` supplied to'+ ' `'+ componentName +'`. Validation failed.' ); } }) };
Requiring Single Child
With
PropTypes.element
you can specify that only a single child can be passed to a component as children.
import PropTypes from'prop-types';
classMyComponentextendsReact.Component{ render(){ // This must be exactly one element or it will warn. const children =this.props.children; return( <div> {children} </div> ); } }
Since ES2022 you can also declare
defaultProps
as static property within a React component class. For more information, see the class public static fields. This modern syntax will require a compilation step to work within older browsers.
The
defaultProps
will be used to ensure that
this.props.name
will have a value if it was not specified by the parent component. The
propTypes
typechecking happens after
defaultProps
are resolved, so typechecking will also apply to the
defaultProps
.
Function Components
If you are using function components in your regular development, you may want to make some small changes to allow PropTypes to be properly applied.
Let’s say you have a component like this:
exportdefaultfunctionHelloWorldComponent({ name }){ return( <div>Hello, {name}</div> ) }
To add PropTypes, you may want to declare the component in a separate function before exporting, like this:
functionHelloWorldComponent({ name }){ return( <div>Hello, {name}</div> ) }
exportdefault HelloWorldComponent
Then, you can add PropTypes directly to the
HelloWorldComponent
:
import PropTypes from'prop-types'
functionHelloWorldComponent({ name }){ return( <div>Hello, {name}</div> ) }
Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components.
If it’s still not clear which type of component you should use for a particular situation, you might find this article on controlled versus uncontrolled inputs to be helpful.
Default Values
In the React rendering lifecycle, the
value
attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a
defaultValue
attribute instead of
value
. Changing the value of
defaultValue
attribute after a component has mounted will not cause any update of the value in the DOM.
Likewise,
<input type="checkbox">
and
<input type="radio">
support
defaultChecked
, and
<select>
and
<textarea>
supports
defaultValue
.
The file input Tag
In HTML, an
<input type="file">
lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API.
<inputtype="file"/>
In React, an
<input type="file" />
is always an uncontrolled component because its value can only be set by a user, and not programmatically.
You should use the File API to interact with the files. The following example shows how to create a ref to the DOM node to access file(s) in a submit handler:
Most people who use React don’t use Web Components, but you may want to, especially if you are using third-party UI components that are written using Web Components.
Web Components often expose an imperative API. For instance, a
video
Web Component might expose
play()
and
pause()
functions. To access the imperative APIs of a Web Component, you will need to use a ref to interact with the DOM node directly. If you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.
Events emitted by a Web Component may not properly propagate through a React render tree.
You will need to manually attach event handlers to handle these events within your React components.
One common confusion is that Web Components use “class” instead of “className”.
This code
will not
work if you transform classes with Babel. See this issue for the discussion.
Include the custom-elements-es5-adapter before you load your web components to fix this issue.
React
is the entry point to the React library. If you load React from a
<script>
tag, these top-level APIs are available on the
React
global. If you use ES6 with npm, you can write
import React from 'react'
. If you use ES5 with npm, you can write
var React = require('react')
.
React components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React components can be defined by subclassing
React.Component
or
React.PureComponent
.
React.Component
React.PureComponent
If you don’t use ES6 classes, you may use the
create-react-class
module instead. See Using React without ES6 for more information.
React components can also be defined as functions which can be wrapped:
React.memo
Creating React Elements
We recommend using JSX to describe what your UI should look like. Each JSX element is just syntactic sugar for calling
React.createElement()
. You will not typically invoke the following methods directly if you are using JSX.
createElement()
createFactory()
See Using React without JSX for more information.
Transforming Elements
React
provides several APIs for manipulating elements:
cloneElement()
isValidElement()
React.Children
Fragments
React
also provides a component for rendering multiple elements without a wrapper.
React.Fragment
Refs
React.createRef
React.forwardRef
Suspense
Suspense lets components “wait” for something before rendering. Today, Suspense only supports one use case: loading components dynamically with
React.lazy
. In the future, it will support other use cases like data fetching.
React.lazy
React.Suspense
Transitions
Transitions
are a new concurrent feature introduced in React 18. They allow you to mark updates as transitions, which tells React that they can be interrupted and avoid going back to Suspense fallbacks for already visible content.
React.startTransition
React.useTransition
Hooks
Hooks
are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks have a dedicated docs section and a separate API reference:
Basic Hooks
useState
useEffect
useContext
Additional Hooks
useReducer
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
useDebugValue
useDeferredValue
useTransition
useId
Library Hooks
useSyncExternalStore
useInsertionEffect
Reference
React.Component
React.Component
is the base class for React components when they are defined using ES6 classes:
See the React.Component API Reference for a list of methods and properties related to the base
React.Component
class.
React.PureComponent
React.PureComponent
is similar to
React.Component
. The difference between them is that
React.Component
doesn’t implement
shouldComponentUpdate()
, but
React.PureComponent
implements it with a shallow prop and state comparison.
If your React component’s
render()
function renders the same result given the same props and state, you can use
React.PureComponent
for a performance boost in some cases.
Note
React.PureComponent
’s
shouldComponentUpdate()
only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend
PureComponent
when you expect to have simple props and state, or use
forceUpdate()
when you know deep data structures have changed. Or, consider using immutable objects to facilitate fast comparisons of nested data.
Furthermore,
React.PureComponent
’s
shouldComponentUpdate()
skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.
React.memo
const MyComponent = React.memo(functionMyComponent(props){ /* render using props */ });
React.memo
is a higher order component.
If your component renders the same result given the same props, you can wrap it in a call to
React.memo
for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.
React.memo
only checks for prop changes. If your function component wrapped in
React.memo
has a
useState
,
useReducer
or
useContext
Hook in its implementation, it will still rerender when state or context change.
By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.
functionMyComponent(props){ /* render using props */ } functionareEqual(prevProps, nextProps){ /* return true if passing nextProps to render would return the same result as passing prevProps to render, otherwise return false */ } exportdefault React.memo(MyComponent, areEqual);
This method only exists as a
performance optimization.
Do not rely on it to “prevent” a render, as this can lead to bugs.
Note
Unlike the
shouldComponentUpdate()
method on class components, the
areEqual
function returns
true
if the props are equal and
false
if the props are not equal. This is the inverse from
shouldComponentUpdate
.
Create and return a new React element of the given type. The type argument can be either a tag name string (such as
'div'
or
'span'
), a React component type (a class or a function), or a React fragment type.
Code written with JSX will be converted to use
React.createElement()
. You will not typically invoke
React.createElement()
directly if you are using JSX. See React Without JSX to learn more.
Clone and return a new React element using
element
as the starting point.
config
should contain all new props,
key
, or
ref
. The resulting element will have the original element’s props with the new props merged in shallowly. New children will replace existing children.
key
and
ref
from the original element will be preserved if no
key
and
ref
present in the
config
.
However, it also preserves
ref
s. This means that if you get a child with a
ref
on it, you won’t accidentally steal it from your ancestor. You will get the same
ref
attached to your new element. The new
ref
or
key
will replace old ones if present.
This API was introduced as a replacement of the deprecated
React.addons.cloneWithProps()
.
createFactory()
React.createFactory(type)
Return a function that produces React elements of a given type. Like
React.createElement()
, the type argument can be either a tag name string (such as
'div'
or
'span'
), a React component type (a class or a function), or a React fragment type.
This helper is considered legacy, and we encourage you to either use JSX or use
React.createElement()
directly instead.
You will not typically invoke
React.createFactory()
directly if you are using JSX. See React Without JSX to learn more.
isValidElement()
React.isValidElement(object)
Verifies the object is a React element. Returns
true
or
false
.
React.Children
React.Children
provides utilities for dealing with the
this.props.children
opaque data structure.
React.Children.map
React.Children.map(children,function[(thisArg)])
Invokes a function on every immediate child contained within
children
with
this
set to
thisArg
. If
children
is an array it will be traversed and the function will be called for each child in the array. If children is
null
or
undefined
, this method will return
null
or
undefined
rather than an array.
Note
If
children
is a
Fragment
it will be treated as a single child and not traversed.
Like
React.Children.map()
but does not return an array.
React.Children.count
React.Children.count(children)
Returns the total number of components in
children
, equal to the number of times that a callback passed to
map
or
forEach
would be invoked.
React.Children.only
React.Children.only(children)
Verifies that
children
has only one child (a React element) and returns it. Otherwise this method throws an error.
Note:
React.Children.only()
does not accept the return value of
React.Children.map()
because it is an array rather than a React element.
React.Children.toArray
React.Children.toArray(children)
Returns the
children
opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice
this.props.children
before passing it down.
Note:
React.Children.toArray()
changes keys to preserve the semantics of nested arrays when flattening lists of children. That is,
toArray
prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.
React.Fragment
The
React.Fragment
component lets you return multiple elements in a
render()
method without creating an additional DOM element:
render(){ return( <React.Fragment> Some text. <h2>A heading</h2> </React.Fragment> ); }
You can also use it with the shorthand
<></>
syntax. For more information, see React v16.2.0: Improved Support for Fragments.
React.createRef
React.createRef
creates a ref that can be attached to React elements via the ref attribute.
React.forwardRef
creates a React component that forwards the ref attribute it receives to another component below in the tree. This technique is not very common but is particularly useful in two scenarios:
Forwarding refs to DOM components
Forwarding refs in higher-order-components
React.forwardRef
accepts a rendering function as an argument. React will call this function with
props
and
ref
as two arguments. This function should return a React node.
// You can now get a ref directly to the DOM button: const ref = React.createRef(); <FancyButtonref={ref}>Click me!</FancyButton>;
In the above example, React passes a
ref
given to
<FancyButton ref={ref}>
element as a second argument to the rendering function inside the
React.forwardRef
call. This rendering function passes the
ref
to the
<button ref={ref}>
element.
As a result, after React attaches the ref,
ref.current
will point directly to the
<button>
DOM element instance.
For more information, see forwarding refs.
React.lazy
React.lazy()
lets you define a component that is loaded dynamically. This helps reduce the bundle size to delay loading components that aren’t used during the initial render.
You can learn how to use it from our code splitting documentation. You might also want to check out this article explaining how to use it in more detail.
// This component is loaded dynamically const SomeComponent = React.lazy(()=>import('./SomeComponent'));
Note that rendering
lazy
components requires that there’s a
<React.Suspense>
component higher in the rendering tree. This is how you specify a loading indicator.
React.Suspense
React.Suspense
lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. In the future we plan to let
Suspense
handle more scenarios such as data fetching. You can read about this in our roadmap.
Today, lazy loading components is the
only
use case supported by
<React.Suspense>
:
// This component is loaded dynamically const OtherComponent = React.lazy(()=>import('./OtherComponent'));
It is documented in our code splitting guide. Note that
lazy
components can be deep inside the
Suspense
tree — it doesn’t have to wrap every one of them. The best practice is to place
<Suspense>
where you want to see a loading indicator, but to use
lazy()
wherever you want to do code splitting.
Note
For content that is already shown to the user, switching back to a loading indicator can be disorienting. It is sometimes better to show the “old” UI while the new UI is being prepared. To do this, you can use the new transition APIs
startTransition
and
useTransition
to mark updates as transitions and avoid unexpected fallbacks.
React.Suspense
in Server Side Rendering
During server side rendering Suspense Boundaries allow you to flush your application in smaller chunks by suspending.
When a component suspends we schedule a low priority task to render the closest Suspense boundary’s fallback. If the component unsuspends before we flush the fallback then we send down the actual content and throw away the fallback.
React.Suspense
during hydration
Suspense boundaries depend on their parent boundaries being hydrated before they can hydrate, but they can hydrate independently from sibling boundaries. Events on a boundary before it is hydrated will cause the boundary to hydrate at a higher priority than neighboring boundaries. Read more
React.startTransition
React.startTransition(callback)
React.startTransition
lets you mark updates inside the provided callback as transitions. This method is designed to be used when
React.useTransition
is not available.
Note:
Updates in a transition yield to more urgent updates such as clicks.
Updates in a transition will not show a fallback for re-suspended content, allowing the user to continue interacting while rendering the update.
React.startTransition
does not provide an
isPending
flag. To track the pending status of a transition see
React.useTransition
.
React lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend
React.Component
:
The only method you
must
define in a
React.Component
subclass is called
render()
. All the other methods described on this page are optional.
We strongly recommend against creating your own base component classes.
In React components, code reuse is primarily achieved through composition rather than inheritance.
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.
The Component Lifecycle
Each component has several “lifecycle methods” that you can override to run code at particular times in the process.
You can use this lifecycle diagram as a cheat sheet.
In the list below, commonly used lifecycle methods are marked as
bold
. The rest of them exist for relatively rare use cases.
Mounting
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
Note:
This method is considered legacy and you should avoid it in new code:
UNSAFE_componentWillMount()
Updating
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
Note:
These methods are considered legacy and you should avoid them in new code:
UNSAFE_componentWillUpdate()
UNSAFE_componentWillReceiveProps()
Unmounting
This method is called when a component is being removed from the DOM:
componentWillUnmount()
Error Handling
These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
static getDerivedStateFromError()
componentDidCatch()
Other APIs
Each component also provides some other APIs:
setState()
forceUpdate()
Class Properties
defaultProps
displayName
Instance Properties
props
state
Reference
Commonly Used Lifecycle Methods
The methods in this section cover the vast majority of use cases you’ll encounter creating React components.
For a visual reference, check out this lifecycle diagram.
render()
render()
The
render()
method is the only required method in a class component.
When called, it should examine
this.props
and
this.state
and return one of the following types:
React elements.
Typically created via JSX. For example,
<div />
and
<MyComponent />
are React elements that instruct React to render a DOM node, or another user-defined component, respectively.
Arrays and fragments.
Let you return multiple elements from render. See the documentation on fragments for more details.
Portals
. Let you render children into a different DOM subtree. See the documentation on portals for more details.
String and numbers.
These are rendered as text nodes in the DOM.
Booleans or
null
or
undefined
. Render nothing. (Mostly exists to support
return test && <Child />
pattern, where
test
is boolean).
The
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.
If you need to interact with the browser, perform your work in
componentDidMount()
or the other lifecycle methods instead. Keeping
render()
pure makes components easier to think about.
Note
render()
will not be invoked if
shouldComponentUpdate()
returns false.
constructor()
constructor(props)
If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.
The constructor for a React component is called before it is mounted. When implementing the constructor for a
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.
Typically, in React constructors are only used for two purposes:
Initializing local state by assigning an object to
this.state
.
Binding event handler methods to an instance.
You
should not call
setState()
in the
constructor()
. Instead, if your component needs to use local state,
assign the initial state to
this.state
directly in the constructor:
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.
This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in
componentWillUnmount()
.
You
may call
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()
is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good 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).
You
may call
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.
If your component implements the
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.
Note
componentDidUpdate()
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()
.
You
should not call
setState()
in
componentWillUnmount()
because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.
Rarely Used Lifecycle Methods
The methods in this section correspond to uncommon use cases. They’re handy once in a while, but most of your components probably don’t need any of them.
You can see most of the methods below on this lifecycle diagram if you click the “Show less common lifecycles” checkbox at the top of it.
shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState)
Use
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.
This method only exists as a
performance optimization.
Do not rely on it to “prevent” a rendering, as this can lead to bugs.
Consider using the built-in
PureComponent
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.
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. Note that returning
false
does not prevent child components from re-rendering when
their
state changes.
We do not recommend doing deep equality checks or using
JSON.stringify()
in
shouldComponentUpdate()
. It is very inefficient and will harm performance.
Currently, if
shouldComponentUpdate()
returns
false
, then
UNSAFE_componentWillUpdate()
,
render()
, and
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()
staticgetDerivedStateFromProps(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.
This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a
<Transition>
component that compares its previous and next children to decide which of them to animate in and out.
Deriving state leads to verbose code and makes your components difficult to think about.
Make sure you’re familiar with simpler alternatives:
If 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 want to
re-compute some data only when a prop changes
, use a memoization helper instead.
If you want to
“reset” some state when a prop changes
, consider either making a component fully controlled or fully uncontrolled with a
key
instead.
This method doesn’t have access to the component instance. If you’d like, you can reuse some code between
getDerivedStateFromProps()
and the other class methods by extracting pure functions of the component props and state outside the class definition.
Note that this method is fired on
every
render, regardless of the cause. This is in contrast to
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()
.
This use case is not common, but it may occur in UIs like a chat thread that need to handle scroll position in a special way.
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; } returnnull; }
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; } }
In the above examples, it is important to read the
scrollHeight
property in
getSnapshotBeforeUpdate
because there may be delays between “render” phase lifecycles (like
render
) and “commit” phase lifecycles (like
getSnapshotBeforeUpdate
and
componentDidUpdate
).
Error boundaries
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
A class component becomes an error boundary if it defines either (or both) of the lifecycle methods
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.
Only use error boundaries for recovering from unexpected exceptions;
don’t try to use them for control flow.
For more details, see
Error Handling in React 16
.
Note
Error boundaries only catch errors in the components
below
them in the tree. An error boundary can’t catch an error within itself.
static getDerivedStateFromError()
staticgetDerivedStateFromError(error)
This lifecycle is invoked after an error has been thrown by a descendant component.
It receives the error that was thrown as a parameter and should return a value to update state.
staticgetDerivedStateFromError(error){// Update state so the next render will show the fallback UI.return{hasError:true};} render(){ if(this.state.hasError){// You can render any custom fallback UIreturn<h1>Something went wrong.</h1>;} returnthis.props.children; } }
Note
getDerivedStateFromError()
is called during the “render” phase, so side-effects are not permitted.
For those use cases, use
componentDidCatch()
instead.
componentDidCatch()
componentDidCatch(error, info)
This lifecycle is invoked after an error has been thrown by a descendant component.
It receives two parameters:
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:
staticgetDerivedStateFromError(error){ // Update state so the next render will show the fallback UI. return{hasError:true}; }
componentDidCatch(error, info){// Example "componentStack":// in ComponentThatThrows (created by App)// in ErrorBoundary (created by App)// in div (created by App)// in ApplogComponentStackToMyService(info.componentStack);} render(){ if(this.state.hasError){ // You can render any custom fallback UI return<h1>Something went wrong.</h1>; }
returnthis.props.children; } }
Production and development builds of React slightly differ in the way
componentDidCatch()
handles errors.
On development, the errors will bubble up to
window
, this means that any
window.onerror
or
window.addEventListener('error', callback)
will intercept the errors that have been caught by
componentDidCatch()
.
On production, instead, the errors will not bubble up, which means any ancestor error handler will only receive errors not explicitly caught by
componentDidCatch()
.
Note
In 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.
Legacy Lifecycle Methods
The lifecycle methods below are marked as “legacy”. They still work, but we don’t recommend using them in the new code. You can learn more about migrating away from legacy lifecycle methods in this blog post.
UNSAFE_componentWillMount()
UNSAFE_componentWillMount()
Note
This 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.
Avoid introducing any side-effects or subscriptions in this method. For those use cases, use
componentDidMount()
instead.
This is the only lifecycle method called on server rendering.
UNSAFE_componentWillReceiveProps()
UNSAFE_componentWillReceiveProps(nextProps)
Note
This 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 inconsistencies
If 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.
Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. Make sure to compare the current and next values if you only want to handle changes.
React doesn’t call
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)
Note
This 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.
Note that you cannot call
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.
Typically, this method can be replaced by
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()
.
Note
UNSAFE_componentWillUpdate()
will not be invoked if
shouldComponentUpdate()
returns false.
Other APIs
Unlike the lifecycle methods above (which React calls for you), the methods below are the methods
you
can call from your components.
There are just two of them:
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.
Think of
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. In the rare case that you need to force the DOM update to be applied synchronously, you may wrap it in
flushSync
, but this may hurt performance.
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.
The first argument is an
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
:
Both
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
.
The second parameter to
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.
You may optionally pass an object as the first argument to
setState()
instead of a function:
setState(stateChange[, callback])
This performs a shallow merge of
stateChange
into the new state, e.g., to adjust a shopping cart item quantity:
this.setState({quantity:2})
This form of
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:
Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:
In depth: When and why are
setState()
calls batched?
In depth: Why isn’t
this.state
updated immediately?
forceUpdate()
component.forceUpdate(callback)
By default, when your component’s state or props change, your component will re-render. If your
render()
method depends on some other data, you can tell React that the component needs re-rendering by calling
forceUpdate()
.
Calling
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.
Normally you should try to avoid all uses of
forceUpdate()
and only read from
this.props
and
this.state
in
render()
.
Class Properties
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:
classCustomButtonextendsReact.Component{ // ... }
CustomButton.defaultProps ={ color:'blue' };
If
props.color
is not provided, it will be set by default to
'blue'
:
render(){ return<CustomButton/>;// props.color will be set to blue }
If
props.color
is set to
null
, it will remain
null
:
render(){ return<CustomButtoncolor={null}/>;// props.color will remain null }
displayName
The
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.
Instance Properties
props
this.props
contains the props that were defined by the caller of this component. See Components and Props for an introduction to props.
In particular,
this.props.children
is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself.
state
The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.
If some value isn’t used for rendering or data flow (for example, a timer ID), you don’t have to put it in the state. Such values can be defined as fields on the component instance.
See State and Lifecycle for more information about the state.
Never mutate
this.state
directly, as calling
setState()
afterwards may replace the mutation you made. Treat
this.state
as if it were immutable.