Search code examples
reactjsreact-nativesetstatereact-state-managementreact-state

setState() block the UI when two setState() run


Here is my componentDidMount() method :

componentDidMount() {
    const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) => {
        x = Math.trunc(x*100);
        this.setState({x})
    });
}

In above method, every 100 millisecond state is changing. I used that state in my render() method as below :

render() {
    const animatedImageStyle = StyleSheet.flatten([
      styles.captureButton,
      {
        transform: [{rotateZ:this.state.x + 'deg'}]
      }
    ])

    return (
      <SideMenu 
        menu={leftMenu}
        isOpen={this.state.isOpenLeftMenu}
        menuPosition={'left'}
        bounceBackOnOverdraw={false}
        onChange={(isOpenLeftMenu) => this.updateLeftMenuState(isOpenLeftMenu)}
      >
        <View>
            <TouchableOpacity 
                activeOpacity={0.5}
                onPress={(this.state.recordingMode == 'camera')?() => this.takePicture():() => this.toggleRecording()}
              > 
                <Image 
                  source={require('../assets/imgs/forRotate.png')}
                  style={animatedImageStyle}
                />
            </TouchableOpacity>
        </View>
      </SideMenu>
    )
}

Now, the problem is that when I trying to open sidemenu, it is not opening, I mean it opening but hanging too much. My whole app hanging too much.

I think that's because of below method :

updateLeftMenuState(isMenuOpen) {
    this.setState({
      isOpenLeftMenu:isMenuOpen
    })
}

Notice that I am updating another state called isOpenLeftMenu, which may blocked during I update state x.

Can anyone tell me what't going wrong here ?


Solution

  • you can move the animation view in a separate component along with subscription logic. So the state update of that component won't affect the SideMenu component.