I'm using the public class field syntax (handler = () => {...}
) to define all my React components' event handlers so that I can use this
for my components without binding them in the constructor
. I'm wondering can I use this syntax to use React life cycle methods as well? Say use componentWillMount
in this way: componentWillMount = () => {...}
What are the pros and cons if defining react's life cycle method with arrow functions?
Is it OK to use arrow functions in render methods? Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions. If you do have performance issues, by all means, optimize!
An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.
Arrow functions don't redefine the value of this within their function body. This makes it a lot easier to predict their behavior when passed as callbacks, and prevents bugs caused by use of this within callbacks.
State and Lifecycle methods are the backbones of any React application, and Hooks enable functional components to implement them efficiently. Hooks allow you to use state and other React features without writing a class as they do not function inside classes.
Each time your function performs a =>
operation it has to create a new function object. This prevents the browser from reusing the same function when rendering multiple copies of the same element which makes optimization by the javascript engine harder to do. This would cause performance issues(, but in most programs, it won't be noticeable).
It is recommended not to use arrow functions for life-cycle methods in React
When should you use arrow functions
There shouldn't be a need in component lifecycle methods to implicitly bind this
(ie: use arrow functions). They are always called from the context of the component, so access to props, state, getState, etc are already available.
So there are no advantages to this pattern. Some disadvantages I can think of are:
this
on a component method, I immediately expect that is going to be called by some other entity downstream, ie: click event handlers passed from parent to child.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With