Using Context breaks components with setState in React Native 0.54
See original GitHub issueReact Native uses React 16.3.0-alpha.1 which has the new context API. However, there’s a bug in the context API which makes the consumer re-render its children every time one of its children call setState
: https://github.com/facebook/react/issues/12218
This breaks components like FlatList
which call setState
internally where you get a stack overflow due to re-render happening thousands of times. The workaround is to wrap FlatList
with a PureComponent
to short-circuit the updates.
It seems to have been fixed here: https://github.com/facebook/react/pull/12254, so we would need to update the React version used by React Native once it’s released.
Environment
Environment: OS: macOS High Sierra 10.13.4 Node: 9.5.0 Yarn: 1.3.2 npm: 5.6.0 Watchman: 4.9.0 Xcode: Xcode 9.2 Build version 9C40b Android Studio: 2.3 AI-162.4069837
Packages: (wanted => installed) react: ^16.3.0-alpha.1 => 16.3.0-alpha.1 react-native: 0.54.2 => 0.54.2
Expected Behavior
Should not cause a stack overflow.
Actual Behavior
Causes a stack overflow.
Steps to Reproduce
It’s not possible to provide a Snack since it uses an older version of React Native. You can create a new project with react-native init
and copy the following code to App.js
:
import * as React from 'react';
import { Text, FlatList } from 'react-native';
const { Consumer } = React.createContext({});
export default class App extends React.Component {
render() {
return (
<Consumer>
{() => {
console.log('re-rendered');
return (
<FlatList
data={Array.from({ length: 100 }).map((_, i) => `Item ${1}`)}
renderItem={({ item }) => <Text>{item}</Text>}
keyExtractor={(item, index) => 'key' + index}
/>
);
}}
</Consumer>
);
}
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:7
- Comments:6 (5 by maintainers)
The React <-> React Native sync has landed in https://github.com/facebook/react-native/commit/4f8328bf2fb71b104baa70178a1e1f9636773c6a. Can you take a look and see if this still happens?
0.56 is the latest version, and it has this fix.