DCR
DCR

Reputation: 15665

do you need to explicitly bind a function?

I have a function called multiply and a component called NumberInputField when I pass the function to the component I use:

<NumberInputField id='1' action={this.multiply} />

but I also have seen:

<NumberInputField id='1' action={this.multiply.bind(this)} />

they both seem to work. Is there a difference? Is one way more acceptable?

Upvotes: 2

Views: 79

Answers (2)

Eric Hasselbring
Eric Hasselbring

Reputation: 1414

Edited:

It depends on what the function is doing. If you need access to state, props, etc. then yes you need to bind it. Best practice is to create it as an arrow function or bind it in the constructor.

If not, then no. But, best practice would be to move that function to a helper file so it can be used again in the future if it is a function that is reusable.

Upvotes: 1

Joshua Underwood
Joshua Underwood

Reputation: 927

When you bind a function, you're giving that function context of the class you're currently in. If, for example, the multiply() function needed to use this.setState() then you would need to use bind so that the function has the appropriate context.

However, it is not a good idea to use bind in your render method. Why? Because each time render is called, the bind will occur again. Instead you can bind the function in your constructor

e.g.

constructor() {
    super();
    this.multiply = this.multiply.bind(this);
}

even better, if you use babel's transform class properties plugin, you can write your functions like so

export default class App extends Component {

    multiply = () => {
       //Automatically knows about "this"
    };

}

While some answers do note that you only need it if you should access "this" in that function. It is important you understand the best practices as well. Do not bind in the render method.

Upvotes: 3

Related Questions