Skip to content

Commit 7b0434f

Browse files
⚡ Optimize PlatformPicker with React.memo (#217)
* Optimize PlatformPicker with React.memo to prevent unnecessary re-renders Co-authored-by: xRahul <1639945+xRahul@users.noreply.github.com> * Fix lint errors in PlatformPickerBenchmark test Co-authored-by: xRahul <1639945+xRahul@users.noreply.github.com> --------- Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> Co-authored-by: xRahul <1639945+xRahul@users.noreply.github.com>
1 parent cb360da commit 7b0434f

2 files changed

Lines changed: 62 additions & 1 deletion

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import React from 'react';
2+
import renderer from 'react-test-renderer';
3+
import PlatformPicker from '../src/components/PlatformPicker';
4+
5+
const mockPickerRender = jest.fn();
6+
7+
jest.mock('react-native', () => {
8+
const ReactLib = require('react');
9+
const View = props => ReactLib.createElement('View', props, props.children);
10+
const Text = props => ReactLib.createElement('Text', props, props.children);
11+
const Picker = props => {
12+
mockPickerRender();
13+
return ReactLib.createElement('Picker', props, props.children);
14+
};
15+
Picker.Item = props => ReactLib.createElement('Picker.Item', props);
16+
17+
return {
18+
View,
19+
Text,
20+
Picker,
21+
StyleSheet: {
22+
create: obj => obj,
23+
flatten: obj => obj,
24+
},
25+
Platform: {
26+
OS: 'ios',
27+
select: obj => obj.ios,
28+
},
29+
};
30+
});
31+
32+
describe('PlatformPicker Performance', () => {
33+
test('renders repeatedly', () => {
34+
mockPickerRender.mockClear();
35+
const handler = () => {};
36+
const selectedValue = 'mobile';
37+
38+
// Initial render
39+
const component = renderer.create(
40+
<PlatformPicker selectedValue={selectedValue} onValueChange={handler} />,
41+
);
42+
43+
expect(mockPickerRender).toHaveBeenCalledTimes(1);
44+
45+
const start = Date.now();
46+
47+
// Update 5000 times
48+
for (let i = 0; i < 5000; i++) {
49+
component.update(
50+
<PlatformPicker
51+
selectedValue={selectedValue}
52+
onValueChange={handler}
53+
/>,
54+
);
55+
}
56+
57+
const end = Date.now();
58+
console.log(`Benchmark Duration: ${end - start}ms`);
59+
console.log(`Picker Render Count: ${mockPickerRender.mock.calls.length}`);
60+
});
61+
});

src/components/PlatformPicker.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,4 @@ const PlatformPicker = ({selectedValue, onValueChange}) => {
2222
);
2323
};
2424

25-
export default PlatformPicker;
25+
export default React.memo(PlatformPicker);

0 commit comments

Comments
 (0)