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.
The
react-dom
package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need to.
import*as ReactDOM from'react-dom';
If you use ES5 with npm, you can write:
var ReactDOM =require('react-dom');
The
react-dom
package also provides modules specific to client and server apps:
These
react-dom
methods are also exported, but are considered legacy:
render()
hydrate()
findDOMNode()
unmountComponentAtNode()
Note:
Both
render
and
hydrate
have been replaced with new client methods in React 18. These methods will warn that your app will behave as if it’s running React 17 (learn more here).
Browser Support
React supports all modern browsers, although some polyfills are required for older versions.
Note
We do not support older browsers that don’t support ES5 methods or microtasks such as Internet Explorer. You may find that your apps do work in older browsers if polyfills such as es5-shim and es5-sham are included in the page, but you’re on your own if you choose to take this path.
Reference
createPortal()
createPortal(child, container)
Creates a portal. Portals provide a way to render children into a DOM node that exists outside the hierarchy of the DOM component.
flushSync()
flushSync(callback)
Force React to flush any updates inside the provided callback synchronously. This ensures that the DOM is updated immediately.
// Force this state update to be synchronous. flushSync(()=>{ setCount(count +1); }); // By this point, DOM is updated.
Note:
flushSync
can significantly hurt performance. Use sparingly.
flushSync
may force pending Suspense boundaries to show their
fallback
state.
flushSync
may also run pending effects and synchronously apply any updates they contain before returning.
flushSync
may also flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.
Legacy Reference
render()
render(element, container[, callback])
Note:
render
has been replaced with
createRoot
in React 18. See createRoot for more info.
Render a React element into the DOM in the supplied
container
and return a reference to the component (or returns
null
for stateless components).
If the React element was previously rendered into
container
, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.
If the optional callback is provided, it will be executed after the component is rendered or updated.
Note:
render()
controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when first called. Later calls use React’s DOM diffing algorithm for efficient updates.
render()
does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children.
render()
currently returns a reference to the root
ReactComponent
instance. However, using this return value is legacy
and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root
ReactComponent
instance, the preferred solution is to attach a
callback ref to the root element.
Using
render()
to hydrate a server-rendered container is deprecated. Use
hydrateRoot()
instead.
hydrate()
hydrate(element, container[, callback])
Note:
hydrate
has been replaced with
hydrateRoot
in React 18. See hydrateRoot for more info.
Same as
render()
, but is used to hydrate a container whose HTML contents were rendered by
ReactDOMServer
. React will attempt to attach event listeners to the existing markup.
React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the warning by adding
suppressHydrationWarning={true}
to the element. It only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates.
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a state variable like
this.state.isClient
, which you can set to
true
in
componentDidMount()
. This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. Note that this approach will make your components slower because they have to render twice, so use it with caution.
Remember to be mindful of user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so if you render something different in the client-only pass, the transition can be jarring. However, if executed well, it may be beneficial to render a “shell” of the application on the server, and only show some of the extra widgets on the client. To learn how to do this without getting the markup mismatch issues, refer to the explanation in the previous paragraph.
unmountComponentAtNode()
unmountComponentAtNode(container)
Note:
unmountComponentAtNode
has been replaced with
root.unmount()
in React 18. See createRoot for more info.
Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns
true
if a component was unmounted and
false
if there was no component to unmount.
findDOMNode()
Note:
findDOMNode
is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated in
StrictMode
.
findDOMNode(component)
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
In most cases, you can attach a ref to the DOM node and avoid using
findDOMNode
at all.
When a component renders to
null
or
false
,
findDOMNode
returns
null
. When a component renders to a string,
findDOMNode
returns a text DOM node containing that value. As of React 16, a component may return a fragment with multiple children, in which case
findDOMNode
will return the DOM node corresponding to the first non-empty child.
Note:
findDOMNode
only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling
findDOMNode()
in
render()
on a component that has yet to be created) an exception will be thrown.
findDOMNode
cannot be used on function components.
The
react-dom/client
package provides client-specific methods used for initializing an app on the client. Most of your components should not need to use this module.
The following methods can be used in client environments:
createRoot()
hydrateRoot()
Browser Support
React supports all modern browsers, although some polyfills are required for older versions.
Note
We do not support older browsers that don’t support ES5 methods or microtasks such as Internet Explorer. You may find that your apps do work in older browsers if polyfills such as es5-shim and es5-sham are included in the page, but you’re on your own if you choose to take this path.
Reference
createRoot()
createRoot(container[, options]);
Create a React root for the supplied
container
and return the root. The root can be used to render a React element into the DOM with
render
:
onRecoverableError
: optional callback called when React automatically recovers from errors.
identifierPrefix
: optional prefix React uses for ids generated by
React.useId
. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix used on the server.
The root can also be unmounted with
unmount
:
root.unmount();
Note:
createRoot()
controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when render is called. Later calls use React’s DOM diffing algorithm for efficient updates.
createRoot()
does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children.
Using
createRoot()
to hydrate a server-rendered container is not supported. Use
hydrateRoot()
instead.
hydrateRoot()
hydrateRoot(container, element[, options])
Same as
createRoot()
, but is used to hydrate a container whose HTML contents were rendered by
ReactDOMServer
. React will attempt to attach event listeners to the existing markup.
hydrateRoot
accepts two options:
onRecoverableError
: optional callback called when React automatically recovers from errors.
identifierPrefix
: optional prefix React uses for ids generated by
React.useId
. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix used on the server.
Note
React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
Render a React element to its initial HTML. Returns a stream with a
pipe(res)
method to pipe the output and
abort()
to abort the request. Fully supports Suspense and streaming of HTML with “delayed” content blocks “popping in” via inline
<script>
tags later. Read more
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
let didError =false; const stream =renderToPipeableStream( <App/>, { onShellReady(){ // The content above all Suspense boundaries is ready. // If something errored before we started streaming, we set the error code appropriately. res.statusCode = didError ?500:200; res.setHeader('Content-type','text/html'); stream.pipe(res); }, onShellError(error){ // Something errored before we could complete the shell so we emit an alternative shell. res.statusCode =500; res.send( '<!doctype html><p>Loading...</p><script src="clientrender.js"></script>' ); }, onAllReady(){ // If you don't want streaming, use this instead of onShellReady. // This will fire after the entire page content is ready. // You can use this for crawlers or static generation.
Streams a React element to its initial HTML. Returns a Promise that resolves to a Readable Stream. Fully supports Suspense and streaming of HTML. Read more
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
let controller =newAbortController(); let didError =false; try{ let stream =awaitrenderToReadableStream( <html> <body>Success</body> </html>, { signal: controller.signal, onError(error){ didError =true; console.error(error); } } );
// This is to wait for all Suspense boundaries to be ready. You can uncomment // this line if you want to buffer the entire HTML instead of streaming it. // You can use this for crawlers or static generation:
This API depends on Web Streams. For Node.js, use
renderToPipeableStream
instead.
renderToNodeStream()
(Deprecated)
ReactDOMServer.renderToNodeStream(element)
Render a React element to its initial HTML. Returns a Node.js Readable stream that outputs an HTML string. The HTML output by this stream is exactly equal to what
ReactDOMServer.renderToString
would return. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
Note:
Server-only. This API is not available in the browser.
The stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like iconv-lite, which provides transform streams for transcoding text.
renderToStaticNodeStream()
ReactDOMServer.renderToStaticNodeStream(element)
Similar to
renderToNodeStream
, except this doesn’t create extra DOM attributes that React uses internally, such as
data-reactroot
. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.
The HTML output by this stream is exactly equal to what
ReactDOMServer.renderToStaticMarkup
would return.
If you plan to use React on the client to make the markup interactive, do not use this method. Instead, use
renderToNodeStream
on the server and
ReactDOM.hydrateRoot()
on the client.
Note:
Server-only. This API is not available in the browser.
The stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like iconv-lite, which provides transform streams for transcoding text.
renderToString()
ReactDOMServer.renderToString(element)
Render a React element to its initial HTML. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
Note
This API has limited Suspense support and does not support streaming.
On the server, it is recommended to use either
renderToPipeableStream
(for Node.js) or
renderToReadableStream
(for Web Streams) instead.
renderToStaticMarkup()
ReactDOMServer.renderToStaticMarkup(element)
Similar to
renderToString
, except this doesn’t create extra DOM attributes that React uses internally, such as
data-reactroot
. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.
If you plan to use React on the client to make the markup interactive, do not use this method. Instead, use
renderToString
on the server and
ReactDOM.hydrateRoot()
on the client.
React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations.
In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute
tabindex
corresponds to the attribute
tabIndex
in React. The exception is
aria-*
and
data-*
attributes, which should be lowercased. For example, you can keep
aria-label
as
aria-label
.
There are a number of attributes that work differently between React and HTML:
checked
The
checked
attribute is supported by
<input>
components of type
checkbox
or
radio
. You can use it to set whether the component is checked. This is useful for building controlled components.
defaultChecked
is the uncontrolled equivalent, which sets whether the component is checked when it is first mounted.
className
To specify a CSS class, use the
className
attribute. This applies to all regular DOM and SVG elements like
<div>
,
<a>
, and others.
If you use React with Web Components (which is uncommon), use the
class
attribute instead.
dangerouslySetInnerHTML
dangerouslySetInnerHTML
is React’s replacement for using
innerHTML
in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out
dangerouslySetInnerHTML
and pass an object with a
__html
key, to remind yourself that it’s dangerous. For example:
Since
for
is a reserved word in JavaScript, React elements use
htmlFor
instead.
onChange
The
onChange
event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior because
onChange
is a misnomer for its behavior and React relies on this event to handle user input in real time.
selected
If you want to mark an
<option>
as selected, reference the value of that option in the
value
of its
<select>
instead.
Check out “The select Tag” for detailed instructions.
style
Note
Some examples in the documentation use
style
for convenience, but
using the
style
attribute as the primary means of styling elements is generally not recommended.
In most cases,
className
should be used to reference classes defined in an external CSS stylesheet.
style
is most often used in React applications to add dynamically-computed styles at render time. See also FAQ: Styling and CSS.
The
style
attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM
style
JavaScript property, is more efficient, and prevents XSS security holes. For example:
Note that styles are not autoprefixed. To support older browsers, you need to supply corresponding style properties:
const divStyle ={ WebkitTransition:'all',// note the capital 'W' here msTransition:'all'// 'ms' is the only lowercase vendor prefix };
functionComponentWithTransition(){ return<divstyle={divStyle}>This should work cross-browser</div>; }
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g.
node.style.backgroundImage
). Vendor prefixes other than
ms
should begin with a capital letter. This is why
WebkitTransition
has an uppercase “W”.
React will automatically append a “px” suffix to certain numeric inline style properties. If you want to use units other than “px”, specify the value as a string with the desired unit. For example:
// Result style: '10px' <divstyle={{height:10}}> Hello World! </div>
// Result style: '10%' <divstyle={{height:'10%'}}> Hello World! </div>
Not all style properties are converted to pixel strings though. Certain ones remain unitless (eg
zoom
,
order
,
flex
). A complete list of unitless properties can be seen here.
suppressContentEditableWarning
Normally, there is a warning when an element with children is also marked as
contentEditable
, because it won’t work. This attribute suppresses that warning. Don’t use this unless you are building a library like Draft.js that manages
contentEditable
manually.
suppressHydrationWarning
If you use server-side React rendering, normally there is a warning when the server and the client render different content. However, in some rare cases, it is very hard or impossible to guarantee an exact match. For example, timestamps are expected to differ on the server and on the client.
If you set
suppressHydrationWarning
to
true
, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don’t overuse it. You can read more about hydration in the
ReactDOM.hydrateRoot()
documentation.
value
The
value
attribute is supported by
<input>
,
<select>
and
<textarea>
components. You can use it to set the value of the component. This is useful for building controlled components.
defaultValue
is the uncontrolled equivalent, which sets the value of the component when it is first mounted.
All Supported HTML Attributes
As of React 16, any standard or custom DOM attributes are fully supported.
React has always provided a JavaScript-centric API to the DOM. Since React components often take both custom and DOM-related props, React uses the
camelCase
convention just like the DOM APIs:
<divtabIndex={-1}/>// Just like node.tabIndex DOM API <divclassName="Button"/>// Just like node.className DOM API <inputreadOnly={true}/>// Just like node.readOnly DOM API
These props work similarly to the corresponding HTML attributes, with the exception of the special cases documented above.
Some of the DOM attributes supported by React include:
accept acceptCharset accessKey action allowFullScreen alt async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked cite classID className colSpan cols content contentEditable contextMenu controls controlsList coords crossOrigin data dateTime default defer dir disabled download draggable encType form formAction formEncType formMethod formNoValidate formTarget frameBorder headers height hidden high href hrefLang htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list loop low manifest marginHeight marginWidth max maxLength media mediaGroup method min minLength multiple muted name noValidate nonce open optimum pattern placeholder poster preload profile radioGroup readOnly rel required reversed role rowSpan rows sandbox scope scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step style summary tabIndex target title type useMap value width wmode wrap
Similarly, all SVG attributes are fully supported: