This is one stop global knowledge base where you can learn about all the products, solutions and support features.
Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI. For many applications, using React will lead to a fast user interface without doing much work to specifically optimize for performance. Nevertheless, there are several ways you can speed up your React application.
If you’re benchmarking or experiencing performance problems in your React apps, make sure you’re testing with the minified production build.
By default, React includes many helpful warnings. These warnings are very useful in development. However, they make React larger and slower so you should make sure to use the production version when you deploy the app.
If you aren’t sure whether your build process is set up correctly, you can check it by installing React Developer Tools for Chrome. If you visit a site with React in production mode, the icon will have a dark background:
If you visit a site with React in development mode, the icon will have a red background:
It is expected that you use the development mode when working on your app, and the production mode when deploying your app to the users.
You can find instructions for building your app for production below.
If your project is built with Create React App, run:
npm run build
This will create a production build of your app in the
build/
folder of your project.
Remember that this is only necessary before deploying to production. For normal development, use
npm start
.
We offer production-ready versions of React and React DOM as single files:
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
Remember that only React files ending with
.production.min.js
are suitable for production.
For the most efficient Brunch production build, install the
terser-brunch
plugin:
# If you use npm
npm install --save-dev terser-brunch
# If you use Yarn
yarn add --dev terser-brunch
Then, to create a production build, add the
-p
flag to the
build
command:
brunch build -p
Remember that you only need to do this for production builds. You shouldn’t pass the
-p
flag or apply this plugin in development, because it will hide useful React warnings and make the builds much slower.
For the most efficient Browserify production build, install a few plugins:
# If you use npm
npm install --save-dev envify terser uglifyify
# If you use Yarn
yarn add --dev envify terser uglifyify
To create a production build, make sure that you add these transforms (the order matters) :
envify
transform ensures the right build environment is set. Make it global (
-g
).
uglifyify
transform removes development imports. Make it global too (
-g
).
terser
for mangling (read why).
For example:
browserify ./index.js \
-g [ envify --NODE_ENV production ] \
-g uglifyify \
| terser --compress --mangle > ./bundle.js
Remember that you only need to do this for production builds. You shouldn’t apply these plugins in development because they will hide useful React warnings, and make the builds much slower.
For the most efficient Rollup production build, install a few plugins:
# If you use npm
npm install --save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser
# If you use Yarn
yarn add --dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser
To create a production build, make sure that you add these plugins (the order matters) :
replace
plugin ensures the right build environment is set.
commonjs
plugin provides support for CommonJS in Rollup.
terser
plugin compresses and mangles the final bundle.
plugins: [
// ...
require('rollup-plugin-replace')({
'process.env.NODE_ENV': JSON.stringify('production')
}),
require('rollup-plugin-commonjs')(),
require('rollup-plugin-terser')(),
// ...
]
For a complete setup example see this gist.
Remember that you only need to do this for production builds. You shouldn’t apply the
terser
plugin or the
replace
plugin with
'production'
value in development because they will hide useful React warnings, and make the builds much slower.
Note:
If you’re using Create React App, please follow the instructions above.
This section is only relevant if you configure webpack directly.
Webpack v4+ will minify your code by default in production mode.
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
optimization: {
minimizer: [new TerserPlugin({ /* additional options here */ })],
},
};
You can learn more about this in webpack documentation.
Remember that you only need to do this for production builds. You shouldn’t apply
TerserPlugin
in development because it will hide useful React warnings, and make the builds much slower.
react-dom
16.5+ and
react-native
0.57+ provide enhanced profiling capabilities in DEV mode with the React DevTools Profiler.
An overview of the Profiler can be found in the blog post “Introducing the React Profiler”.
A video walkthrough of the profiler is also available on YouTube.
If you haven’t yet installed the React DevTools, you can find them here:
Note
A production profiling bundle of
react-dom
is also available asreact-dom/profiling
.
Read more about how to use this bundle at fb.me/react-profiling
Note
Before React 17, we use the standard User Timing API to profile components with the chrome performance tab.
For a more detailed walkthrough, check out this article by Ben Schwarz.
If your application renders long lists of data (hundreds or thousands of rows), we recommend using a technique known as “windowing”. This technique only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created.
react-window and react-virtualized are popular windowing libraries. They provide several reusable components for displaying lists, grids, and tabular data. You can also create your own windowing component, like Twitter did, if you want something more tailored to your application’s specific use case.
React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a “virtual DOM”, but it works the same way on React Native.
When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM.
Even though React only updates the changed DOM nodes, re-rendering still takes some time. In many cases it’s not a problem, but if the slowdown is noticeable, you can speed all of this up by overriding the lifecycle function
shouldComponentUpdate
, which is triggered before the re-rendering process starts. The default implementation of this function returns
true
, leaving React to perform the update:
shouldComponentUpdate(nextProps, nextState) {
return true;
}
If you know that in some situations your component doesn’t need to update, you can return
false
from
shouldComponentUpdate
instead, to skip the whole rendering process, including calling
render()
on this component and below.
In most cases, instead of writing
shouldComponentUpdate()
by hand, you can inherit from
React.PureComponent
. It is equivalent to implementing
shouldComponentUpdate()
with a shallow comparison of current and previous props and state.
Here’s a subtree of components. For each one,
SCU
indicates what
shouldComponentUpdate
returned, and
vDOMEq
indicates whether the rendered React elements were equivalent. Finally, the circle’s color indicates whether the component had to be reconciled or not.
Since
shouldComponentUpdate
returned
false
for the subtree rooted at C2, React did not attempt to render C2, and thus didn’t even have to invoke
shouldComponentUpdate
on C4 and C5.
For C1 and C3,
shouldComponentUpdate
returned
true
, so React had to go down to the leaves and check them. For C6
shouldComponentUpdate
returned
true
, and since the rendered elements weren’t equivalent React had to update the DOM.
The last interesting case is C8. React had to render this component, but since the React elements it returned were equal to the previously rendered ones, it didn’t have to update the DOM.
Note that React only had to do DOM mutations for C6, which was inevitable. For C8, it bailed out by comparing the rendered React elements, and for C2’s subtree and C7, it didn’t even have to compare the elements as we bailed out on
shouldComponentUpdate
, and
render
was not called.
If the only way your component ever changes is when the
props.color
or the
state.count
variable changes, you could have
shouldComponentUpdate
check that:
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
In this code,
shouldComponentUpdate
is just checking if there is any change in
props.color
or
state.count
. If those values don’t change, the component doesn’t update. If your component got more complex, you could use a similar pattern of doing a “shallow comparison” between all the fields of
props
and
state
to determine if the component should update. This pattern is common enough that React provides a helper to use this logic - just inherit from
React.PureComponent
. So this code is a simpler way to achieve the same thing:
class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {count: 1};
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
Most of the time, you can use
React.PureComponent
instead of writing your own
shouldComponentUpdate
. It only does a shallow comparison, so you can’t use it if the props or state may have been mutated in a way that a shallow comparison would miss.
This can be a problem with more complex data structures. For example, let’s say you want a
ListOfWords
component to render a comma-separated list of words, with a parent
WordAdder
component that lets you click a button to add a word to the list. This code does
not
work correctly:
class ListOfWords extends React.PureComponent {
render() {
return <div>{this.props.words.join(',')}</div>;
}
}
class WordAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
words: ['marklar']
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// This section is bad style and causes a bug
const words = this.state.words;
words.push('marklar');
this.setState({words: words});
}
render() {
return (
<div>
<button onClick={this.handleClick} />
<ListOfWords words={this.state.words} />
</div>
);
}
}
The problem is that
PureComponent
will do a simple comparison between the old and new values of
this.props.words
. Since this code mutates the
words
array in the
handleClick
method of
WordAdder
, the old and new values of
this.props.words
will compare as equal, even though the actual words in the array have changed. The
ListOfWords
will thus not update even though it has new words that should be rendered.
The simplest way to avoid this problem is to avoid mutating values that you are using as props or state. For example, the
handleClick
method above could be rewritten using
concat
as:
handleClick() {
this.setState(state => ({
words: state.words.concat(['marklar'])
}));
}
ES6 supports a spread syntax for arrays which can make this easier. If you’re using Create React App, this syntax is available by default.
handleClick() {
this.setState(state => ({
words: [...state.words, 'marklar'],
}));
};
You can also rewrite code that mutates objects to avoid mutation, in a similar way. For example, let’s say we have an object named
colormap
and we want to write a function that changes
colormap.right
to be
'blue'
. We could write:
function updateColorMap(colormap) {
colormap.right = 'blue';
}
To write this without mutating the original object, we can use Object.assign method:
function updateColorMap(colormap) {
return Object.assign({}, colormap, {right: 'blue'});
}
updateColorMap
now returns a new object, rather than mutating the old one.
Object.assign
is in ES6 and requires a polyfill.
Object spread syntax makes it easier to update objects without mutation as well:
function updateColorMap(colormap) {
return {...colormap, right: 'blue'};
}
This feature was added to JavaScript in ES2018.
If you’re using Create React App, both
Object.assign
and the object spread syntax are available by default.
When you deal with deeply nested objects, updating them in an immutable way can feel convoluted. If you run into this problem, check out Immer or immutability-helper. These libraries let you write highly readable code without losing the benefits of immutability.
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
ReactDOM.createPortal(child, container)
The first argument (
child
) is any
renderable React child, such as an element, string, or fragment. The second argument (
container
) is a DOM element.
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
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:
<html>
<body>
<div id="app-root"></div>
<div id="modal-root"></div>
</body>
</html>
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');
class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}
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);
}
componentWillUnmount() {
modalRoot.removeChild(this.el);
}
render() {
return ReactDOM.createPortal( this.props.children, this.el ); }
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {clicks: 0};
this.handleClick = this.handleClick.bind(this);
}
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 (
<div onClick={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>
);
}
}
function Child() {
// The click event on this button will bubble up to parent, // because there is no 'onClick' attribute defined return (
<div className="modal">
<button>Click</button> </div>
);
}
const root = ReactDOM.createRoot(appRoot);
root.render(<Parent />);
Try it on CodePen
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.
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
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:
render(
<App>
<Profiler id="Navigation" onRender={callback}> <Navigation {...props} />
</Profiler>
<Main {...props} />
</App>
);
Multiple
Profiler
components can be used to measure different parts of an application:
render(
<App>
<Profiler id="Navigation" onRender={callback}> <Navigation {...props} />
</Profiler>
<Profiler id="Main" onRender={callback}> <Main {...props} />
</Profiler>
</App>
);
Profiler
components can also be nested to measure different components within the same subtree:
render(
<App>
<Profiler id="Panel" onRender={callback}> <Panel {...props}>
<Profiler id="Content" onRender={callback}> <Content {...props} />
</Profiler>
<Profiler id="PreviewPane" onRender={callback}> <PreviewPane {...props} />
</Profiler>
</Panel>
</Profiler>
</App>
);
Note
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.
function onRenderCallback(
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
-
id
prop of the
Profiler
tree that has just committed.
phase: "mount" | "update"
-
actualDuration: number
-
Profiler
and its descendants for the current update.
React.memo
,
useMemo
,
shouldComponentUpdate
).
baseDuration: number
-
render
time for each individual component within the
Profiler
tree.
startTime: number
-
commitTime: number
-
interactions: Set
-
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
Normally you would define a React component as a plain JavaScript class:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
If you don’t use ES6 yet, you may use the
create-react-class
module instead:
var createReactClass = require('create-react-class');
var Greeting = createReactClass({
render: function() {
return <h1>Hello, {this.props.name}</h1>;
}
});
The API of ES6 classes is similar to
createReactClass()
with a few exceptions.
With functions and ES6 classes
defaultProps
is defined as a property on the component itself:
class Greeting extends React.Component {
// ...
}
Greeting.defaultProps = {
name: 'Mary'
};
With
createReactClass()
, you need to define
getDefaultProps()
as a function on the passed object:
var Greeting = createReactClass({
getDefaultProps: function() {
return {
name: 'Mary'
};
},
// ...
});
In ES6 classes, you can define the initial state by assigning
this.state
in the constructor:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}
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};
},
// ...
});
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:
class SayHello extends React.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 (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}
With
createReactClass()
, this is not necessary because it binds all methods:
var SayHello = createReactClass({
getInitialState: function() {
return {message: 'Hello!'};
},
handleClick: function() {
alert(this.state.message);
},
render: function() {
return (
<button onClick={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:
class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
}
// Using an arrow here binds the method:
handleClick = () => {
alert(this.state.message);
};
render() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}
You also have a few other options:
onClick={(e) => this.handleClick(e)}
.
createReactClass
.
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 SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.forEach(clearInterval);
}
};
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>
);
}
});
const root = ReactDOM.createRoot(document.getElementById('example'));
root.render(<TickTock />);
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.
For example, this code written with JSX:
class Hello extends React.Component {
render() {
return <div>Hello {this.props.toWhat}</div>;
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Hello toWhat="World" />);
can be compiled to this code that does not use JSX:
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));
If you’re curious to see more examples of how JSX is converted to JavaScript, you can try out the online Babel compiler.
The component can either be provided as a string, as a subclass of
React.Component
, or a plain function.
If you get tired of typing
React.createElement
so much, one common pattern is to assign a shorthand:
const e = React.createElement;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(e('div', null, 'Hello World'));
If you use this shorthand form for
React.createElement
, it can be almost as convenient to use React without JSX.
Alternatively, you can refer to community projects such as
react-hyperscript
and
hyperscript-helpers
which offer a terser syntax.
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:
key
prop.
In practice, these assumptions are valid for almost all practical use cases.
When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.
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()
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:
<div className="before" title="stuff" />
<div className="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:
<div style={{color: 'red', fontWeight: 'bold'}} />
<div style={{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.
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()
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:
<ul>
<li>first</li>
<li>second</li>
</ul>
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
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:
<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>
<ul>
<li>Connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>
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.
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:
<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
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:
<li key={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.
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.
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.