Normally, when you return an element from a component’s render method, it’s mounted into the DOM as a child of the nearest parent node:
render(){ // React mounts a new div and renders the children into it return( <div>{this.props.children} </div>); }
However, sometimes it’s useful to insert a child into a different location in the DOM:
render(){ // React does *not* create a new div. It renders the children into `domNode`. // `domNode` is any valid DOM node, regardless of its location in the DOM. return ReactDOM.createPortal( this.props.children, domNode); }
A typical use case for portals is when a parent component has an
overflow: hidden
or
z-index
style, but you need the child to visually “break out” of its container. For example, dialogs, hovercards, and tooltips.
Note:
When working with portals, remember that managing keyboard focus becomes very important.
For modal dialogs, ensure that everyone can interact with them by following the WAI-ARIA Modal Authoring Practices.
Try it on CodePen
Event Bubbling Through Portals
Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. Features like context work exactly the same regardless of whether the child is a portal, as the portal still exists in the
React tree
regardless of position in the
DOM tree
.
This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the containing
React tree
, even if those elements are not ancestors in the
DOM tree
. Assuming the following HTML structure:
A
Parent
component in
#app-root
would be able to catch an uncaught, bubbling event from the sibling node
#modal-root
.
// These two containers are siblings in the DOM const appRoot = document.getElementById('app-root'); const modalRoot = document.getElementById('modal-root');
componentDidMount(){ // The portal element is inserted in the DOM tree after // the Modal's children are mounted, meaning that children // will be mounted on a detached DOM node. If a child // component requires to be attached to the DOM tree // immediately when mounted, for example to measure a // DOM node, or uses 'autoFocus' in a descendant, add // state to Modal and only render the children when Modal // is inserted in the DOM tree. modalRoot.appendChild(this.el); }
handleClick(){// This will fire when the button in Child is clicked,// updating Parent's state, even though button// is not direct descendant in the DOM.this.setState(state=>({clicks: state.clicks +1}));} render(){ return( <divonClick={this.handleClick}><p>Number of clicks: {this.state.clicks}</p> <p> Open up the browser DevTools to observe that the button is not a child of the div with the onClick handler. </p> <Modal><Child/></Modal></div> ); } }
functionChild(){ // The click event on this button will bubble up to parent,// because there is no 'onClick' attribute definedreturn( <divclassName="modal"> <button>Click</button></div> ); }
Catching an event bubbling up from a portal in a parent component allows the development of more flexible abstractions that are not inherently reliant on portals. For example, if you render a
<Modal />
component, the parent can capture its events regardless of whether it’s implemented using portals.
Is this page useful?
Edit this page
Profiler API – React
Profiler API
The
Profiler
measures how often a React application renders and what the “cost” of rendering is.
Its purpose is to help identify parts of an application that are slow and may benefit from
optimizations such as memoization.
Note:
Profiling adds some additional overhead, so
it is disabled in the production build
.
To opt into production profiling, React provides a special production build with profiling enabled.
Read more about how to use this build at fb.me/react-profiling
Usage
A
Profiler
can be added anywhere in a React tree to measure the cost of rendering that part of the tree.
It requires two props: an
id
(string) and an
onRender
callback (function) which React calls any time a component within the tree “commits” an update.
For example, to profile a
Navigation
component and its descendants:
Although
Profiler
is a light-weight component, it should be used only when necessary; each use adds some CPU and memory overhead to an application.
onRender
Callback
The
Profiler
requires an
onRender
function as a prop.
React calls this function any time a component within the profiled tree “commits” an update.
It receives parameters describing what was rendered and how long it took.
functiononRenderCallback( id,// the "id" prop of the Profiler tree that has just committed phase,// either "mount" (if the tree just mounted) or "update" (if it re-rendered) actualDuration,// time spent rendering the committed update baseDuration,// estimated time to render the entire subtree without memoization startTime,// when React began rendering this update commitTime,// when React committed this update interactions // the Set of interactions belonging to this update ){ // Aggregate or log render timings... }
Let’s take a closer look at each of the props:
id: string
-
The
id
prop of the
Profiler
tree that has just committed.
This can be used to identify which part of the tree was committed if you are using multiple profilers.
phase: "mount" | "update"
-
Identifies whether the tree has just been mounted for the first time or re-rendered due to a change in props, state, or hooks.
actualDuration: number
-
Time spent rendering the
Profiler
and its descendants for the current update.
This indicates how well the subtree makes use of memoization (e.g.
React.memo
,
useMemo
,
shouldComponentUpdate
).
Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.
baseDuration: number
-
Duration of the most recent
render
time for each individual component within the
Profiler
tree.
This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization).
startTime: number
-
Timestamp when React began rendering the current update.
commitTime: number
-
Timestamp when React committed the current update.
This value is shared between all profilers in a commit, enabling them to be grouped if desirable.
interactions: Set
-
Set of “interactions” that were being traced when the update was scheduled (e.g. when
render
or
setState
were called).
Note
Interactions can be used to identify the cause of an update, although the API for tracing them is still experimental.
Learn more about it at fb.me/react-interaction-tracing
With
createReactClass()
, you have to provide a separate
getInitialState
method that returns the initial state:
var Counter =createReactClass({ getInitialState:function(){ return{count:this.props.initialCount}; }, // ... });
Autobinding
In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don’t automatically bind
this
to the instance. You’ll have to explicitly use
.bind(this)
in the constructor:
classSayHelloextendsReact.Component{ constructor(props){ super(props); this.state ={message:'Hello!'}; // This line is important! this.handleClick =this.handleClick.bind(this); }
handleClick(){ alert(this.state.message); }
render(){ // Because `this.handleClick` is bound, we can use it as an event handler. return( <buttononClick={this.handleClick}> Say hello </button> ); } }
With
createReactClass()
, this is not necessary because it binds all methods:
var SayHello =createReactClass({ getInitialState:function(){ return{message:'Hello!'}; },
render:function(){ return( <buttononClick={this.handleClick}> Say hello </button> ); } });
This means writing ES6 classes comes with a little more boilerplate code for event handlers, but the upside is slightly better performance in large applications.
If the boilerplate code is too unattractive to you, you may use ES2022 Class Properties syntax:
// Using an arrow here binds the method: handleClick=()=>{ alert(this.state.message); };
render(){ return( <buttononClick={this.handleClick}> Say hello </button> ); } }
You also have a few other options:
Bind methods in the constructor.
Use arrow functions, e.g.
onClick={(e) => this.handleClick(e)}
.
Keep using
createReactClass
.
Mixins
Note:
ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes.
We also found numerous issues in codebases using mixins, and don’t recommend using them in the new code.
This section exists only for the reference.
Sometimes very different components may share some common functionality. These are sometimes called cross-cutting concerns.
createReactClass
lets you use a legacy
mixins
system for that.
One common use case is a component wanting to update itself on a time interval. It’s easy to use
setInterval()
, but it’s important to cancel your interval when you don’t need it anymore to save memory. React provides lifecycle methods that let you know when a component is about to be created or destroyed. Let’s create a simple mixin that uses these methods to provide an easy
setInterval()
function that will automatically get cleaned up when your component is destroyed.
var createReactClass =require('create-react-class');
var TickTock =createReactClass({ mixins:[SetIntervalMixin],// Use the mixin getInitialState:function(){ return{seconds:0}; }, componentDidMount:function(){ this.setInterval(this.tick,1000);// Call a method on the mixin }, tick:function(){ this.setState({seconds:this.state.seconds +1}); }, render:function(){ return( <p> React has been running for {this.state.seconds} seconds. </p> ); } });
If a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component.
JSX is not a requirement for using React. Using React without JSX is especially convenient when you don’t want to set up compilation in your build environment.
Each JSX element is just syntactic sugar for calling
React.createElement(component, props, ...children)
. So, anything you can do with JSX can also be done with just plain JavaScript.
React provides a declarative API so that you don’t have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React’s “diffing” algorithm so that component updates are predictable while being fast enough for high-performance apps.
When you use React, at a single point in time you can think of the
render()
function as creating a tree of React elements. On the next state or props update, that
render()
function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.
There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the state of the art algorithms have a complexity in the order of O(n
3
) where n is the number of elements in the tree.
If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:
Two elements of different types will produce different trees.
The developer can hint at which child elements may be stable across different renders with a
key
prop.
In practice, these assumptions are valid for almost all practical use cases.
The Diffing Algorithm
When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.
Elements Of Different Types
Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from
<a>
to
<img>
, or from
<Article>
to
<Comment>
, or from
<Button>
to
<div>
- any of those will lead to a full rebuild.
When tearing down a tree, old DOM nodes are destroyed. Component instances receive
componentWillUnmount()
. When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive
UNSAFE_componentWillMount()
and then
componentDidMount()
. Any state associated with the old tree is lost.
Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:
<div> <Counter/> </div>
<span> <Counter/> </span>
This will destroy the old
Counter
and remount a new one.
Note:
This method is considered legacy and you should avoid it in new code:
UNSAFE_componentWillMount()
DOM Elements Of The Same Type
When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For example:
<divclassName="before"title="stuff"/>
<divclassName="after"title="stuff"/>
By comparing these two elements, React knows to only modify the
className
on the underlying DOM node.
When updating
style
, React also knows to update only the properties that changed. For example:
<divstyle={{color:'red',fontWeight:'bold'}}/>
<divstyle={{color:'green',fontWeight:'bold'}}/>
When converting between these two elements, React knows to only modify the
color
style, not the
fontWeight
.
After handling the DOM node, React then recurses on the children.
Component Elements Of The Same Type
When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls
UNSAFE_componentWillReceiveProps()
,
UNSAFE_componentWillUpdate()
and
componentDidUpdate()
on the underlying instance.
Next, the
render()
method is called and the diff algorithm recurses on the previous result and the new result.
Note:
These methods are considered legacy and you should avoid them in new code:
UNSAFE_componentWillUpdate()
UNSAFE_componentWillReceiveProps()
Recursing On Children
By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.
For example, when adding an element at the end of the children, converting between these two trees works well:
React will match the two
<li>first</li>
trees, match the two
<li>second</li>
trees, and then insert the
<li>third</li>
tree.
If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly:
React will mutate every child instead of realizing it can keep the
<li>Duke</li>
and
<li>Villanova</li>
subtrees intact. This inefficiency can be a problem.
Keys
In order to solve this issue, React supports a
key
attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a
key
to our inefficient example above can make the tree conversion efficient:
Now React knows that the element with key
'2014'
is the new one, and the elements with the keys
'2015'
and
'2016'
have just moved.
In practice, finding a key is usually not hard. The element you are going to display may already have a unique ID, so the key can just come from your data:
<likey={item.id}>{item.name}</li>
When that’s not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. The key only has to be unique among its siblings, not globally unique.
As a last resort, you can pass an item’s index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.
Reorders can also cause issues with component state when indexes are used as keys. Component instances are updated and reused based on their key. If the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways.
Here is an example of the issues that can be caused by using indexes as keys on CodePen, and here is an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues.
Tradeoffs
It is important to remember that the reconciliation algorithm is an implementation detail. React could rerender the whole app on every action; the end result would be the same. Just to be clear, rerender in this context means calling
render
for all components, it doesn’t mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.
We are regularly refining the heuristics in order to make common use cases faster. In the current implementation, you can express the fact that a subtree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will rerender that full subtree.
Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.
The algorithm will not try to match subtrees of different component types. If you see yourself alternating between two component types with very similar output, you may want to make it the same type. In practice, we haven’t found this to be an issue.
Keys should be stable, predictable, and unique. Unstable keys (like those produced by
Math.random()
) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries.
Avoid using refs for anything that can be done declaratively.
For example, instead of exposing
open()
and
close()
methods on a
Dialog
component, pass an
isOpen
prop to it.
Don’t Overuse Refs
Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy. See the Lifting State Up guide for examples of this.
Note
The examples below have been updated to use the
React.createRef()
API introduced in React 16.3. If you are using an earlier release of React, we recommend using callback refs instead.
Creating Refs
Refs are created using
React.createRef()
and attached to React elements via the
ref
attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
When a ref is passed to an element in
render
, a reference to the node becomes accessible at the
current
attribute of the ref.
const node =this.myRef.current;
The value of the ref differs depending on the type of the node:
When the
ref
attribute is used on an HTML element, the
ref
created in the constructor with
React.createRef()
receives the underlying DOM element as its
current
property.
When the
ref
attribute is used on a custom class component, the
ref
object receives the mounted instance of the component as its
current
.
You may not use the
ref
attribute on function components
because they don’t have instances.
The examples below demonstrate the differences.
Adding a Ref to a DOM Element
This code uses a
ref
to store a reference to a DOM node:
classCustomTextInputextendsReact.Component{ constructor(props){ super(props); // create a ref to store the textInput DOM element this.textInput = React.createRef();this.focusTextInput =this.focusTextInput.bind(this); }
focusTextInput(){ // Explicitly focus the text input using the raw DOM API // Note: we're accessing "current" to get the DOM node this.textInput.current.focus();}
render(){ // tell React that we want to associate the <input> ref // with the `textInput` that we created in the constructor return( <div> <input type="text" ref={this.textInput}/><input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
React will assign the
current
property with the DOM element when the component mounts, and assign it back to
null
when it unmounts.
ref
updates happen before
componentDidMount
or
componentDidUpdate
lifecycle methods.
Adding a Ref to a Class Component
If we wanted to wrap the
CustomTextInput
above to simulate it being clicked immediately after mounting, we could use a ref to get access to the custom input and call its
focusTextInput
method manually:
By default,
you may not use the
ref
attribute on function components
because they don’t have instances:
functionMyFunctionComponent(){return<input/>; }
classParentextendsReact.Component{ constructor(props){ super(props); this.textInput = React.createRef();} render(){ // This will *not* work! return( <MyFunctionComponentref={this.textInput}/>); } }
If you want to allow people to take a
ref
to your function component, you can use
forwardRef
(possibly in conjunction with
useImperativeHandle
), or you can convert the component to a class.
You can, however,
use the
ref
attribute inside a function component
as long as you refer to a DOM element or a class component:
functionCustomTextInput(props){ // textInput must be declared here so the ref can refer to itconst textInput =useRef(null); functionhandleClick(){ textInput.current.focus();}
return( <div> <input type="text" ref={textInput}/><input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); }
Exposing DOM Refs to Parent Components
In rare cases, you might want to have access to a child’s DOM node from a parent component. This is generally not recommended because it breaks component encapsulation, but it can occasionally be useful for triggering focus or measuring the size or position of a child DOM node.
While you could add a ref to the child component, this is not an ideal solution, as you would only get a component instance rather than a DOM node. Additionally, this wouldn’t work with function components.
If you use React 16.3 or higher, we recommend to use ref forwarding for these cases.
Ref forwarding lets components opt into exposing any child component’s ref as their own
. You can find a detailed example of how to expose a child’s DOM node to a parent component in the ref forwarding documentation.
If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can use this alternative approach and explicitly pass a ref as a differently named prop.
When possible, we advise against exposing DOM nodes, but it can be a useful escape hatch. Note that this approach requires you to add some code to the child component. If you have absolutely no control over the child component implementation, your last option is to use
findDOMNode()
, but it is discouraged and deprecated in
StrictMode
.
Callback Refs
React also supports another way to set refs called “callback refs”, which gives more fine-grain control over when refs are set and unset.
Instead of passing a
ref
attribute created by
createRef()
, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.
The example below implements a common pattern: using the
ref
callback to store a reference to a DOM node in an instance property.
this.textInput =null; this.setTextInputRef=element=>{this.textInput = element;}; this.focusTextInput=()=>{// Focus the text input using the raw DOM APIif(this.textInput)this.textInput.focus();};}
componentDidMount(){ // autofocus the input on mount this.focusTextInput();}
render(){ // Use the `ref` callback to store a reference to the text input DOM // element in an instance field (for example, this.textInput). return( <div> <input type="text" ref={this.setTextInputRef}/> <input type="button" value="Focus the text input" onClick={this.focusTextInput}/> </div> ); } }
React will call the
ref
callback with the DOM element when the component mounts, and call it with
null
when it unmounts. Refs are guaranteed to be up-to-date before
componentDidMount
or
componentDidUpdate
fires.
You can pass callback refs between components like you can with object refs that were created with
React.createRef()
.
In the example above,
Parent
passes its ref callback as an
inputRef
prop to the
CustomTextInput
, and the
CustomTextInput
passes the same function as a special
ref
attribute to the
<input>
. As a result,
this.inputElement
in
Parent
will be set to the DOM node corresponding to the
<input>
element in the
CustomTextInput
.
Legacy API: String Refs
If you worked with React before, you might be familiar with an older API where the
ref
attribute is a string, like
"textInput"
, and the DOM node is accessed as
this.refs.textInput
. We advise against it because string refs have some issues, are considered legacy, and
are likely to be removed in one of the future releases
.
Note
If you’re currently using
this.refs.textInput
to access refs, we recommend using either the callback pattern or the
createRef
API instead.
Caveats with callback refs
If the
ref
callback is defined as an inline function, it will get called twice during updates, first with
null
and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the
ref
callback as a bound method on the class, but note that it shouldn’t matter in most cases.