DEV Community

Discussion on: Creating React components without this. #nothis

Collapse
 
imichael profile image
✨iMichael✨ • Edited

Fat arrow functions make old complaints about "this" moot, especially in React. Instead of

 increment(ctx) {
    ctx.setState(state => ({ count: state.count + 1 }))
  }

simply do:

 increment = () => {
    this.setState({count: this.state.count + 1 })
 }

Benefits:

  • It's idiomatic.
  • It looks great.
  • You don't have to bind this or reason about what "this" is at all.
  • If you also write Python or Ruby, your mental model can be this == self.

#thisIsFine

Collapse
 
joelnet profile image
JavaScript Joel

This is absolutely a fantastic solution and it definitely solves one of this's problems. This is a perfect example of that.

I still prefer to eliminate this completely. I don't want to have to ask if the function has been written correctly so that this behaves the way I expect it.

I don't have to worry about "it's okay to use here, this way, but not over here." It's easier for me to program without it.

It's much like null. An even simpler concept than this. We know to put nullchecks all over.

// check that null
if (x) {
  x.y()
}

// shortcut check
x && x.y()

But no matter how hard we try, we are still destined to run into NullReferenceException.

And much like Douglas Crockford says...

"I was very surprised to discover that my programs got better. It was not a hardship to not use this. It was actually a benefit. My programs got smaller and easier and you know, that's what we're all looking for" -- Douglas Crockford

... banning this in your programs, much like null won't be a hardship. It will become a benefit, making your programs smaller and easier!

The only way to eliminate 100% of this related bugs, is to eliminate this.

Cheers!

Collapse
 
josefjelinek profile image
Josef Jelinek • Edited

Unfortunately, this code is not idiomatic as you should pass a function to the setState in this case or else from several increments in a row most get ignored as the state is updated asynchronously and they will have a stale state... nothis FTW is what I take feom this comment in the end...