Reputation: 10214
Arrow functions are often used on methods that needs bindings to handle events.
Everywhere in the documentation and examples, lifecycle methods (render
, componentWillMount
, constructor
, ...) are defined as regular functions, this ends up with mixed methods declaration style inside components.
Is it safe to use arrow functions for all component methods ?
I know it works fine for simple case, I'm looking for all potential downsides.
Upvotes: 0
Views: 905
Reputation: 9251
Yes it is safe to use arrow functions if you want to for consistency.
componentDidMount(){
console.log(this)
}
returns:
App {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternalFiber: FiberNode, …}
context: {}
props: {}
refs: {}
state: null
updater:{isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_reactInternalFiber:FiberNode {tag: 2, key: null, type: ƒ, stateNode: App, return: FiberNode, …}
_reactInternalInstance:{_processChildContext: ƒ}
isMounted:(...)
replaceState:(...)
__proto__:Component
And
componentDidMount = () => {
console.log(this)
}
returns:
App {props: {…}, context: {…}, refs: {…}, updater: {…}, componentDidMount: ƒ, …}
componentDidMount:ƒ ()
context:{}
props:{}
refs:{}
state:null
updater:{isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_reactInternalFiber:FiberNode {tag: 2, key: null, type: ƒ, stateNode: App, return: FiberNode, …}
_reactInternalInstance:{_processChildContext: ƒ}
isMounted:(...)
replaceState:(...)
__proto__:Component
Both these methods log the exact same class except the class with the componentDidMount = () => {}
has componentDidMount as an attribute as opposed to a method but is still called in the same way.
Upvotes: 2