Skip to content

Instantly share code, notes, and snippets.

@curtiswilkinson
Last active March 6, 2017 22:42
Show Gist options
  • Save curtiswilkinson/8e2e9f384f8a5c4021307d2cfc636fe0 to your computer and use it in GitHub Desktop.
Save curtiswilkinson/8e2e9f384f8a5c4021307d2cfc636fe0 to your computer and use it in GitHub Desktop.
Class Component Context Binding
// Binding in Constructor, this is the currently recommended method in the React documentation and what I'm used to using
// It can look kinda bad if you use a lot of them, BUT it does keep the render method clean and avoid repetition of binding
class Component extends React.Component<any, any> {
constructor(props) {
super(props)
this.state = {
bool: false
}
this.handleFunction = this.handleFunction.bind(this)
}
handleFunction(event) {
this.setState({
bool: true
})
}
render() {
return (
<button onClick={this.handleFunction}>Hi</button>
)
}
}
// Binding in the render function
// I am STRONGLY against this as it causes a re-binding on every event trigger
// This is an unneccessary performances hit and muddles the render function
class Component extends React.Component<any, any> {
constructor(props) {
super(props)
this.state = {
bool: false
}
}
handleFunction(event) {
this.setState({
bool: true
})
}
render() {
return (
<button onClick={this.handleFunction.bind(this)}>Hi</button>
)
}
}
// Wrapping in an anonmous funtion upon each usage of the class method
/*
Quote from some react tooling:
Creating new anonymous functions (with either the function syntax or ES2015 arrow syntax) inside the render call stack works against pure component rendering.
When doing an equality check between two lambdas,
React will always consider them unequal values and force the component to re-render more often than necessary.
*/
class Component extends React.Component<any, any> {
constructor(props) {
super(props)
this.state = {
bool: false
}
}
handleFunction(event) {
this.setState({
bool: true
})
}
render() {
return (
<button onClick={() => this.handleFunction}>Hi</button>
)
}
}
// Declaring methods using arrow functions
// This is marked as "experimental" BUT I've done some research and it looks like it's in frequent use
// I personally think this syntax is the cleanest way, and it keeps any binding concerns out of the render function
class Component extends React.Component<any, any> {
constructor(props) {
super(props)
this.state = {
bool: false
}
}
handleFunction = (event) => {
this.setState({
bool: true
})
}
render() {
return (
<button onClick={this.handleFunction}>Hi</button>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment