DEV Community

Discussion on: JavaScript 101: Arrow Functions

Collapse
 
zeddotes profile image
zeddotes

The lexically bound this context is probably the most important quality of thicc arrow functions.

Collapse
 
andrewbrooks profile image
Andrew Brooks 👨‍💻

Agreed. It helps with some of the strange and unexpected behavior of this.

Collapse
 
sameerchandra profile image
Sameer Chandra Nimushakavi

Being a react developer, I mostly use arrow functions to bind this context

Collapse
 
itsjzt profile image
Saurabh Sharma

I tend to use hooks in new code and avoid this altogether.

Thread Thread
 
daveclarke profile image
daveclarke

Can you please provide an example of this (using hooks not this).

Thread Thread
 
itsjzt profile image
Saurabh Sharma

why would you need this when you don't use classes.

Thread Thread
 
daveclarke profile image
daveclarke

Sorry I'm just confused what you mean by hooks. Hoping you might paste in an example?

Thread Thread
 
itsjzt profile image
Saurabh Sharma

Classical React example of Counter

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

    onClick(e) {
        this.setState({
            count: this.state.count + 1
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                {/* this is needed here  */} 
                <button onClick={this.onClick.bind(this)}>Count Up!!</button>
            </div>
        )
    }
}

and after using React Hooks

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

know more about react hooks.

Collapse
 
davegomez profile image
David Gómez

You are not binding the context by using an arrow function, it doesn't work that way.

More info here: github.com/getify/You-Dont-Know-JS...