Is it possible to also use arrow functions with the new React Hook syntax? what will be the difference and/or could this cause problems?
documentation syntax:
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
arrow function:
const Example = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map , reduce , or forEach . Use function declarations for functions you'd call by name (because they're hoisted). Use arrow functions for callbacks (because they tend to be terser).
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.
Learn more at the React docs. If you use arrow functions within render , each call to render will create new function objects. If you then pass these functions to child elements via props , optimizations based on PureComponent or shouldComponentUpdate will fail (as the arrow function props will change on every render).
The short answer is: yes you can.
Arrow functions and function declarations/expressions are not equivalent. However, if the function you want to replace does not use this
, arguments
and is not called with new
, then you are free to use whatever style you prefer.
The difference between declaring functional component using function
or const
would be the same as the difference between functional expressions
and functional declaration
For instance Function declarations
load before any code is executed while Function expressions
load only when the interpreter reaches that line of code i.e rendering a functional component created using function
syntax can be done before it is defined in the code while if its defined using expression
then it needs to be declared before using
So in short function declarations
are hoisted whereas function expressions
are not
In terms of using both the above syntaxes to create components you can use either as long as you use hoisting into account
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