Last active
January 20, 2020 01:54
-
-
Save FanchenBao/ab429de0e73a6283613b84100aa6cfe7 to your computer and use it in GitHub Desktop.
Demo code to show that fat arrow function and binding causes re-rendering in react native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {PureComponent} from 'react'; | |
import { | |
View, | |
Text, | |
TouchableHighlight, | |
TouchableOpacity, | |
} from 'react-native'; | |
class Demo extends PureComponent { | |
constructor(props) { | |
super(props); | |
this.state = { | |
foo: false, | |
}; | |
} | |
/** | |
* Press "change state" to cause re-rendering of ParentComponent. This is expected. | |
* Observe the console output to see whether ChildComponent gets re-rendered as well. | |
* Ideally, ChildComponent should not be re-rendered, because nothing should change | |
* in ChildComponent while ParentComponent gets re-rendered. | |
*/ | |
render() { | |
return ( | |
<View> | |
<ParentComponent prop1={this.state.foo} /> | |
<TouchableHighlight | |
onPress={() => this.setState({foo: !this.state.foo})}> | |
<Text>change state</Text> | |
</TouchableHighlight> | |
</View> | |
); | |
} | |
} | |
class ChildComponent extends PureComponent { | |
/** | |
* Pressing "Click Me" does not cause any re-rendering. It is used to | |
* show consistency of ChildComponent behavior with different return | |
* statement in ParentComponent. | |
*/ | |
render() { | |
console.log('ChildComponent rendered'); | |
return ( | |
<TouchableOpacity onPress={this.props.cb}> | |
<View> | |
<Text>Click Me</Text> | |
</View> | |
</TouchableOpacity> | |
); | |
} | |
} | |
class ParentComponent extends PureComponent { | |
_print = () => console.log('clicked'); | |
_anotherPrint() { | |
console.log(this.props.prop1); | |
} | |
/** | |
* Test with each return statement to see whether ChildComponent re-renders | |
* with ParentComponent. Note that ParentComponent is supposed to be re-rendered, | |
* but ChildComponent should not be re-rendered. However, fat arrow function and | |
* binding both lead to ChilComponent being re-rendered. | |
*/ | |
render() { | |
console.log(`ParentComponent rendered after ${this.props.prop1}`); | |
return ( | |
// <ChildComponent cb={() => console.log('clicked')}/> | |
// <ChildComponent cb={this._print} /> | |
<ChildComponent cb={this._anotherPrint.bind(this)} /> | |
); | |
} | |
} | |
export default Demo; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment