0
# React Addons Perf
1
2
React Addons Perf is a performance profiling tool for React applications that provides detailed insights into component render times, wasted renders, and DOM operations. It helps developers identify performance bottlenecks and optimization opportunities by measuring and analyzing React component behavior during development.
3
4
## Package Information
5
6
- **Package Name**: react-addons-perf
7
- **Package Type**: npm
8
- **Language**: JavaScript (with Flow types)
9
- **Installation**: `npm install react-addons-perf`
10
11
## Core Imports
12
13
```javascript
14
import Perf from 'react-addons-perf';
15
```
16
17
For CommonJS:
18
19
```javascript
20
var Perf = require('react-addons-perf');
21
```
22
23
For React with addons bundle:
24
25
```javascript
26
var Perf = React.addons.Perf;
27
```
28
29
## Basic Usage
30
31
```javascript
32
import Perf from 'react-addons-perf';
33
34
// Start profiling
35
Perf.start();
36
37
// Perform React operations (renders, updates, etc.)
38
// ... your app code here ...
39
40
// Stop profiling
41
Perf.stop();
42
43
// View results
44
Perf.printWasted(); // Most useful - shows wasted renders
45
Perf.printInclusive(); // Shows inclusive render times
46
Perf.printExclusive(); // Shows exclusive render times
47
Perf.printOperations(); // Shows DOM operations
48
```
49
50
## Architecture
51
52
React Addons Perf integrates with React's development build to collect performance measurements:
53
54
- **Development-Only**: All functionality is disabled in production builds for security and performance
55
- **ReactDebugTool Integration**: Uses React's internal `ReactDebugTool` API to capture timing data during component lifecycle events
56
- **Session-Based**: Collects data between `start()` and `stop()` calls, storing measurements in `flushHistory`
57
- **Hook-Based Collection**: Registers hooks for lifecycle events (`render`, `componentDidMount`, etc.) to measure execution time
58
- **Console Integration**: Outputs formatted tables using `console.table()` for easy analysis
59
- **Data Analysis**: Provides multiple views of the same performance data for different optimization insights
60
- **Component Tree Tracking**: Maintains snapshots of React's component tree structure to provide contextual performance data
61
62
## Capabilities
63
64
### Profiling Control
65
66
Control when performance measurements are collected.
67
68
```javascript { .api }
69
/**
70
* Start performance measurement session
71
* No-op in production builds
72
*/
73
function start(): void;
74
75
/**
76
* Stop performance measurement session
77
* No-op in production builds
78
*/
79
function stop(): void;
80
81
/**
82
* Check if profiler is currently running
83
* @returns false in production builds
84
*/
85
function isRunning(): boolean;
86
```
87
88
### Measurement Data Retrieval
89
90
Access raw and processed performance measurement data.
91
92
```javascript { .api }
93
/**
94
* Get measurement data from last profiling session
95
* @returns Array of HistoryItem objects containing measurements, operations, and tree snapshots. Empty array in production builds.
96
*/
97
function getLastMeasurements(): FlushHistory;
98
99
/**
100
* Calculate exclusive render times (excluding child components)
101
* @param flushHistory - Optional measurement data, defaults to getLastMeasurements()
102
* @returns Array of exclusive time statistics
103
*/
104
function getExclusive(flushHistory?: FlushHistory): ExclusiveStats[];
105
106
/**
107
* Calculate inclusive render times (including child components)
108
* @param flushHistory - Optional measurement data, defaults to getLastMeasurements()
109
* @returns Array of inclusive time statistics
110
*/
111
function getInclusive(flushHistory?: FlushHistory): InclusiveStats[];
112
113
/**
114
* Identify components that rendered without DOM changes (wasted renders)
115
* @param flushHistory - Optional measurement data, defaults to getLastMeasurements()
116
* @returns Array of wasted render statistics
117
*/
118
function getWasted(flushHistory?: FlushHistory): WastedStats[];
119
120
/**
121
* Get DOM operations performed during measurement
122
* @param flushHistory - Optional measurement data, defaults to getLastMeasurements()
123
* @returns Array of DOM operation records
124
*/
125
function getOperations(flushHistory?: FlushHistory): OperationStats[];
126
```
127
128
### Console Output
129
130
Display formatted performance data in the browser console.
131
132
```javascript { .api }
133
/**
134
* Print exclusive render times to console table
135
* @param flushHistory - Optional measurement data
136
*/
137
function printExclusive(flushHistory?: FlushHistory): void;
138
139
/**
140
* Print inclusive render times to console table
141
* @param flushHistory - Optional measurement data
142
*/
143
function printInclusive(flushHistory?: FlushHistory): void;
144
145
/**
146
* Print wasted render analysis to console table
147
* @param flushHistory - Optional measurement data
148
*/
149
function printWasted(flushHistory?: FlushHistory): void;
150
151
/**
152
* Print DOM operations to console table
153
* @param flushHistory - Optional measurement data
154
*/
155
function printOperations(flushHistory?: FlushHistory): void;
156
```
157
158
### Deprecated Methods
159
160
Legacy methods maintained for backwards compatibility.
161
162
```javascript { .api }
163
/**
164
* @deprecated Use printOperations() instead
165
* Print DOM operations to console table
166
*/
167
function printDOM(measurements: FlushHistory): void;
168
169
/**
170
* @deprecated Use getWasted() instead
171
* Get wasted render statistics
172
*/
173
function getMeasurementsSummaryMap(measurements: FlushHistory): WastedStats[];
174
```
175
176
## Types
177
178
```javascript { .api }
179
// Core measurement data structure
180
type FlushHistory = HistoryItem[];
181
type DebugID = number;
182
183
interface HistoryItem {
184
duration: number;
185
measurements: Measurement[];
186
operations: Operation[];
187
treeSnapshot: TreeSnapshot;
188
}
189
190
interface Measurement {
191
timerType: TimerType;
192
instanceID: DebugID;
193
duration: number;
194
}
195
196
type TimerType =
197
| 'ctor'
198
| 'render'
199
| 'componentWillMount'
200
| 'componentWillUnmount'
201
| 'componentWillReceiveProps'
202
| 'shouldComponentUpdate'
203
| 'componentWillUpdate'
204
| 'componentDidUpdate'
205
| 'componentDidMount';
206
207
interface TreeSnapshot {
208
[key: DebugID]: {
209
displayName: string;
210
text: string;
211
updateCount: number;
212
childIDs: DebugID[];
213
ownerID: DebugID;
214
parentID: DebugID;
215
};
216
}
217
218
interface Operation {
219
instanceID: DebugID;
220
type: string;
221
payload: any;
222
}
223
224
// Statistics returned by get* methods
225
interface ExclusiveStats {
226
key: string;
227
instanceCount: number;
228
counts: { [timerType: string]: number };
229
durations: { [timerType: string]: number };
230
totalDuration: number;
231
}
232
233
interface InclusiveStats {
234
key: string;
235
instanceCount: number;
236
inclusiveRenderDuration: number;
237
renderCount: number;
238
}
239
240
interface WastedStats {
241
key: string;
242
instanceCount: number;
243
inclusiveRenderDuration: number;
244
renderCount: number;
245
}
246
247
interface OperationStats {
248
flushIndex: number;
249
instanceID: DebugID;
250
key: string;
251
type: string;
252
ownerID: DebugID;
253
payload: any;
254
}
255
```
256
257
## Usage Examples
258
259
### Basic Profiling Workflow
260
261
```javascript
262
import Perf from 'react-addons-perf';
263
264
// Start measurement
265
Perf.start();
266
267
// Trigger React renders
268
ReactDOM.render(<MyApp />, container);
269
270
// Stop measurement
271
Perf.stop();
272
273
// Analyze results - most useful first
274
Perf.printWasted(); // Identify unnecessary re-renders
275
Perf.printInclusive(); // See total render times including children
276
Perf.printExclusive(); // See render times excluding children
277
Perf.printOperations(); // See actual DOM changes
278
```
279
280
### Programmatic Analysis
281
282
```javascript
283
import Perf from 'react-addons-perf';
284
285
// Collect measurements
286
Perf.start();
287
// ... React operations ...
288
Perf.stop();
289
290
// Get raw data for custom analysis
291
const measurements = Perf.getLastMeasurements();
292
const wasted = Perf.getWasted(measurements);
293
294
// Find components with most wasted time
295
const topWasted = wasted
296
.sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration)
297
.slice(0, 5);
298
299
console.log('Top 5 components with wasted renders:', topWasted);
300
```
301
302
### Multiple Profiling Sessions
303
304
```javascript
305
import Perf from 'react-addons-perf';
306
307
// First session
308
Perf.start();
309
// ... first set of operations ...
310
Perf.stop();
311
const firstSession = Perf.getLastMeasurements();
312
313
// Second session
314
Perf.start();
315
// ... second set of operations ...
316
Perf.stop();
317
const secondSession = Perf.getLastMeasurements();
318
319
// Compare sessions
320
console.log('First session wasted:', Perf.getWasted(firstSession));
321
console.log('Second session wasted:', Perf.getWasted(secondSession));
322
```
323
324
## Important Notes
325
326
### Development-Only Tool
327
328
React Addons Perf only works in development builds of React. In production builds:
329
- All methods return safe default values (`false`, `[]`, `undefined`)
330
- A warning is displayed once per session when methods are called
331
- No performance overhead is introduced
332
333
### Performance Impact
334
335
The profiler itself introduces some performance overhead during measurement. Use it only when actively debugging performance issues, not in production.
336
337
### Browser Console Integration
338
339
The `print*` methods use `console.table()` to display formatted results. Ensure your browser's developer tools are open to see the output.
340
341
### Wasted Renders Analysis
342
343
`printWasted()` and `getWasted()` are typically the most useful methods as they identify components that re-rendered without producing DOM changes - the primary optimization target for React applications.