Low performance in React Native with Redux
I have discovered some issues with performance in my react native app. It seems to be caused by react-redux bundle.
As you can see in the video
there is a significant delay between action dispatching and view rendering. On real devices it looks even worse. There are no API calls in this example. Only simple actions dispatching and state changes. On other hand Facebook Flux implementation and simple call of setState work much more faster.
Any ideas how to improve the app performance?
I am using react: v15.2.1, react-native: v0.29.2, react-redux: v4.4.5, View
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {Map} from 'immutable';
import * as testActions from '../reducers/test/testActions';
import {Actions} from 'react-native-router-flux';
const actions = [
testActions
];
function mapStateToProps(state) {
return {
...state
};
}
function mapDispatchToProps(dispatch) {
const creators = Map()
.merge(...actions)
.filter(value => typeof value === 'function')
.toObject();
return {
actions: bindActionCreators(creators, dispatch),
dispatch
};
}
........
<View style={styles.box}>
{PRICE_FILTERS.map(filter =>{
let price_cont_style = {};
let price_text_style = {};
if (filter.id == PRICE_FILTERS[3].id){
price_cont_style.marginRight = 0;
}
if (filter.id == this.props.test.price){
price_cont_style.backgroundColor = 'black';
price_text_style.color = 'white';
}
return(
<TouchableOpacity
key={filter.id}
style={[styles.price_cont, price_cont_style]}
onPress={()=>this.props.actions.setPrice(filter.id)}>
<Text
style={[styles.price_text, price_text_style]}>
{filter.label}
</Text>
</TouchableOpacity>
);
})}
</View>
......
export default connect(mapStateToProps, mapDispatchToProps)(PerformanceTest);
Actions
const {
TEST_SET_PRICE,
} = require('../../lib/constants').default;
export function setPrice(filter) {
return {
type: TEST_SET_PRICE,
payload: filter
};
}
Reducer
const {
TEST_SET_PRICE,
} = require('../../lib/constants').default;
const InitialState = require('./testInitialState').default;
export default function authReducer(state = InitialState, action) {
switch (action.type) {
case TEST_SET_PRICE:
if (state.price!=action.payload){
return {price:action.payload}
} else{
return state;
}
}
return state;
}
Your mapDispatchToProps function looks pretty hairy. Why are you using an immutable Map there? Initializing the Map, merging, filtering, and then converting back to an object is quite computationally expensive. That will run a lot, possibly every time the store's state is updated. I would bet that is your performance bottleneck.
I think you could simplify it to:
function mapDispatchToProps(dispatch) {
return {
setPrice(id) {
dispatch(testActions.setPrice(id))
},
}
}
Your mapStateToProps function could also be optimized a little. Just return state instead of return { ...state }, there's no need to copy the tree there.
Thank you for the advice but i see same delays after applying your changes. This makes me sad because i really like redux and would like to use it for further projects
Hm, darn. If you link to a reproduction in a separate repo someone may be able to help out more.
Rest assured, setting a single value in the store and re-rendering a component is definitely, definitely performant — React, React Native, or otherwise.
Yes, i definitely should create separate simple project for testing. still hope it's a result of libraries conflict. I supposed i have to use only actions/reducers for containers rerendering and passing props for other components. and did not use setState at all. but maybe i got Redux wrong
@lourd If mapDispatchToProps doesn't depend on props (function.length === 1), I'm pretty sure it is only run once per component instance.
@alsh76 Your mapStateToProps will cause your component to rerender every time any action is fired. You should have it be more picky about what parts of state it needs.
Right, thanks for the correction. Having just read through #416 and #407, I know you know what you're talking about 😉
@jimbolla there is the only action in my example. and button pressing causes the only dispatching and the only rendering. the issue happens because of delay between dispatching and rendering. not because of multiple rerenderings.
@alsh76 Have you tried you demo without any middleware (including redux-logger)?
@foiseworth I tried to remove redux-logger and all console.log from the code. It did not help - same delays.
Actually it was a test page from my current project that uses redux-thunk and react-native-router-flux as well as some other libraries.
i am gonna create test project with minimal dependencies and put it on github but honestly i need thunk and router - if the issue is caused by them i will be forced using Flux. With Flux it works good enough
@lourd, @jimbolla, @foiseworth As it turned out the cause of this issue is all components from navigation chain are staying unmounted and get rerendered behind of the visible scene See more details here Possible navigation issue in React Native/Redux app
So it seems not a redux issue but nevertheless I would be very grateful for advices how to handle multiple unmounted components from navigation stack in the best way. I am checking in shouldComponentUpdate if current component is visible but maybe there is the better way?
@alsh76 please test your example with the last react-redux@next. I have almost same problem and update doesn't fix it :(
@max-mykhailenko as i figured out my performance issues were caused by navigation system. when the user navigate through pages like this Scene A => Scene B => Scene C all components A, B, C are staying mounted. Because all reducers are combined into one any action dispatching causes passing props to every mounted component.
For example if the user makes any changes and dispatch them in Scene C all mounted components A, B, C are receiving props and getting rendered in same order A => B => C. If components A and B are big enough (e.g. big ScrollView list) it causes visible delays between Scene C actions and Scene C rendering as in my example
a workaround for this - do not allow rendering of not visible components in shouldComponentUpdate. it resolved my performance issue
i hope it will help you
@alsh76 Thanks for response. I use NavigatorExperimental and also saw lags, but with react-native-router-flux I got good performance. How do you check your active screen for shouldComponentUpdate?
@max-mykhailenko i am using react-native-router-flux. as well as RN Navigator it keeps all components from navigation stack mounted and all of them are rendered together.
with react-native-router-flux you can use your own reducer to detect start of navigation as in their example REDUX_FLUX ActionConst.BACK_ACTION for Actions.pop() and ActionConst.JUMP for tabs switching. First reducer's param contains scene key and name.
also it's important to detect end of navigation (transition between scenes). No rendering should be allowed in transition time. When navigator animation and rendering happen simultaneously it causes freezes and delays in my app. No event is fired at the end of transition. I am using InteractionManager to detect end of navigation.
if you are using NavigatorExperimental that's even simpler you have all callbacks out of the box https://facebook.github.io/react-native/docs/navigation.html#step-4-create-a-navigation-stack
and common rule i came to - the less renderings the better.
@alsh76 How did you did you check if components were visible?
@aljux, I use NativationExperimental but I imagine the flux one is similar in the sense that a list of routes will be maintained with an index to indicate "where we are". You can easily calculate the "distance" between the index and the requested route
@alsh76 I have had a lot of problems with performance on NativationExperimental. Aside from the trick abovem, another trick that made a HUGE ( ;-) ) difference is the following:
render(){
const { navigationState, onNavigate, onBack } = this.props;
return (
<NavigationCardStack
onNavigateBack={this.navigateBack}
navigationState={navigationState}
renderScene={this._renderScene}
renderHeader={this._renderHeader}
onTransitionStart={this._navigationStart}
onTransitionEnd={this._navigationComplete}
/>
);
in the navigationStart and End methods I set a state boolean 'navigating'. When it's true, I force the sceneComponent to not re-render through shouldComponentUpdate.
Another issue you may or may not have is that there are many more render cycles than people often realize. If you don't have a system to "guard" against fetch requests being unnecessarily re-executed with every render cycle, you will also see a big negative performance impact and even recursive loops.
@aljux just watched for navigation events and keep full navigation history and a key of visible scene. code for react-native-router-flux looks like
reducerCreate(params){
const defaultReducer = Reducer(params);
return (state, action)=>{
switch (action.type) {
case ActionConst.PUSH:
// current scene key is action.key
break;
case ActionConst.BACK_ACTION:
// ....
break;
case ActionConst.JUMP:
// tab switching
break;
case ActionConst.FOCUS:
//can be useful
InteractionManager.runAfterInteractions(....);
break;
}
return defaultReducer(state, action);
}
}
render() {
return (
<Router createReducer={this.reducerCreate} hideNavBar={true}>
<Scene key="root" >
....
maybe in recent versions you can get foreground scene directly. should check that
@mschipperheyn yes, thank you for pointing out. I forgot to mention about blocking re-rendering during scene-to-scene transition. If not using NativationExperimental then should use
InteractionManager.runAfterInteractions. This callback is run on the end of navigation animation - the only way to detect end of the animation in my case
@alsh76, @mschipperheyn Thanks. Im using the regular Navigator component together with redux. But I cant figure out how to check inside the component which index that is currently on top? Since the navigator it self does not have that kind of property?
Ok yeah navigation experimental does have that property. Don't know about the one u are using. I understood that fb wants to release some. Kind out of out of the box based on navigation experimental. Don't know ur time frame