Skip to content

REACT Best Practices Binding to `this` Scope

Patrick Alvin Luwum edited this page Jun 20, 2018 · 1 revision

Use .bind() in best way

There are two ways of binding the custom component’s this scope.

  1. Binding them in constructor.(Do this)

image

With this way only one extra function is created at the time of component creation, and that function is used even when render is executed again.

  1. Binding at the time of passing as prop value (Avoid this).

image

.bind() method creates a new function each time it is run, this method would lead to a new function being created every time when the render function executes. This has performance implications. In small applications we cannot notice them, however, in large applications we can notice them.

Solution:

  • It's better to bind your custom functions in constructor.
  • There is a Babel plugin called Class properties transform. You can write auto-bound function using the fat-arrow syntax.

image

If we see the above code there are no functions to bind.