Bulent Gorkem
Posted on May 6, 2023
React functional components have become more popular than React class components in recent times. Hence we don’t need to rely on use of often misunderstood "this" keyword to access member variables, methods. We used to add a lot of mysterious bind(this)
methods to our handlers in constructors before.
this.checkedHandler = this.checkedHandler.bind(this);
Together with lambda syntax used in class methods we don't need this ceremony anymore.
If you want to understand why, the code sample below explains briefly.
import React from "react";
export default class App extends React.Component {
constructor(props: React.PropsWithChildren) {
super(props);
}
handleThis() {
console.log("handle ", this);
}
handleThisWithLambda = ()=> {
console.log('handle that', this)
}
render() {
return (
<div className="App">
<button onClick={this.handleThis}>Handle This </button>
<button onClick={this.handleThisWithLambda}>Handle That </button> </div>
);
}
}
There are 2 methods: handleThis
and handleThisWithLambda
First one prints undefined
as this
, because in strict-mode this
value is undefined when run outside of any object, ie. the event handler, unless it was bound by the function called, hence the use of ...bind.this( )
The second one with the lambda syntax though prints the correct App instance we are running in.
What is the difference?
If you copy-paste this code to a code transpiler, like typescript playground which converts it old ECMAScript 2017 code, you will spot the difference in how lambda syntax is translated inside the class code
export default class App extends React.Component {
constructor(props) {
super(props);
this.handleThisWithLambda = () => {
console.log('handle that', this);
};
}
handleThis() {
console.log("handle ", this);
}
...
}
As you can see handleThisWithLambda
code moved into the constructor function, hence created with a closure to the this
instance. So it is already doing the same job bind.this
was doing previously for the legacy method case.
In React Functional components, you don't need this or bind.this anymore, as every thing is inside the same function closure anyway.
Hope this helps!
Posted on May 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.