1

as far as I know we cannot use this keyword in arrow functions. However, in react I have seen that this is possible. I was wondering how this is possible. Example:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

https://reactjs.org/docs/hooks-state.html

joe gates
  • 459
  • 1
  • 5
  • 15
  • 1
    You *can* use `this` in arrow functions, they just don't have their *own* contexts. So inside an arrow function `this` refers to the *enclosing* scope's context, in this case the component instance. – jonrsharpe Dec 03 '20 at 11:15

2 Answers2

1

Arrow functions doesn't bind this (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). It is totally okey to use this inside arrow functions but you have to be aware that it's not bound to that function. In the example you have posted that is actually really good because it is bound to the class instead so you can access the state.

If you instead would rewrite your onClick handler to use a function statement instead this would be bound to that function instead of your component instance and state wouldn't be accessible.

<button onClick={function() { this.setState({ count: this.state.count + 1 }) }}>
  Click me
</button>
Thejool
  • 514
  • 4
  • 9
0

In an arrow function, this means the same thing within the function body as it does outside of it. Which means that if you use arrow functions within your component’s render or lifecycle methods, they can use this and this.setState with no surprises.

Abu Sufian
  • 991
  • 1
  • 6
  • 15