What is the difference between arrow functions and regular functions inside React functional components (no longer using class components)?
Beside the differences you've already pointed out (lexical scope), arrow functions (and function expressions) are not hoisted, and as such cannot be called before they are defined. See my example. This is in my opinion not a problem, since code that relies on hoisting is much harder to reason about.
React really doesn't care about which one you use (nor can it detect it).
const A = () => {
const name = getName();
function getName() {
return 'praffn';
}
// Will not work
// const getName = () => 'praffn';
return <p>Hi, {name}</p>;
}
ReactDOM.render(<A/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Since you are not accessing the this
context, both will both behave the same.
To understand more, you can check how babel is transpiring to the ECMA:
const handleClick2 = () => {
console.log('handleClick2 executed...');
this.x=3
}
will be transpiled as:
"use strict";
var _this = void 0;
var handleClick2 = function handleClick2() {
console.log('handleClick2 executed...');
_this.x = 3;
};
Link to babel notepad