UNPKG

2.27 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 * @format
9 */
10
11'use strict';
12
13const React = require('react');
14
15opaque type DoNotCommitUsageOfPureComponentDebug = {...};
16
17/**
18 * Identifies which prop or state changes triggered a re-render of a PureComponent. Usage:
19 *
20 * Change `extends React.PureComponent` to `extends PureComponentDebug` or inject it
21 * everywhere by putting this line in your app setup:
22 *
23 * React.PureComponent = require('PureComponentDebug');
24 *
25 * Should only be used for local testing, and will trigger a flow failure if you try to
26 * commit any usages.
27 */
28class PureComponentDebug<
29 P: DoNotCommitUsageOfPureComponentDebug,
30 S: ?Object = void,
31> extends React.Component<P, S> {
32 shouldComponentUpdate(nextProps: P, nextState: S): boolean {
33 const tag = this.constructor.name;
34 let ret = false;
35 const prevPropsKeys = Object.keys(this.props);
36 const nextPropsKeys = Object.keys(nextProps);
37 if (prevPropsKeys.length !== nextPropsKeys.length) {
38 ret = true;
39 console.warn(
40 'PureComponentDebug: different prop keys',
41 tag,
42 prevPropsKeys.filter(key => !nextPropsKeys.includes(key)),
43 nextPropsKeys.filter(key => !prevPropsKeys.includes(key)),
44 );
45 }
46 const prevStateKeys = Object.keys(this.state || {});
47 const nextStateKeys = Object.keys(nextState || {});
48 if (prevStateKeys.length !== nextStateKeys.length) {
49 ret = true;
50 console.warn(
51 'PureComponentDebug: different state keys',
52 tag,
53 prevStateKeys.filter(key => !nextStateKeys.includes(key)),
54 nextStateKeys.filter(key => !prevStateKeys.includes(key)),
55 );
56 }
57 for (const key in this.props) {
58 if (this.props[key] !== nextProps[key]) {
59 ret = true;
60 console.warn('PureComponentDebug: different prop values', tag, key);
61 }
62 }
63 for (const key in this.state) {
64 if (this.state[key] !== (nextState || {})[key]) {
65 ret = true;
66 console.warn('PureComponentDebug: different state values', tag, key);
67 }
68 }
69 return ret;
70 }
71}
72
73module.exports = PureComponentDebug;