Syntax Comparison
| Method | Syntax Example |
|---|---|
| Function Declaration | function MyComponent(props) { ... } |
| Const Arrow Function | const MyComponent = (props) => { ... } |
Key Differences to Consider
IMP : CONTEXT IS NOT AVAILABE IN ARROW FUNCTIONS, HENCE YOU CANNOT USE "this" KEYWORD IN ARROW FUNCTIONS.
- Hoisting: You can use a component defined with the
functionkeyword before it appears in your code because it is "hoisted" to the top of the scope. Components defined withconstmust be defined before they are used. - Exporting: Using the
functionkeyword allows you to useexport defaulton the same line as the definition (e.g.,export default function MyComponent() {}), which you cannot do withconst. - "export default" cannot be combined with "const" in the same statement. They must be split on separate statements. If you still want to use arrow syntax to declare a function, drop the "const" keyword and also DROP THE NAME OF FUNCTION. It becomes anonymous export, which is not a problem for default export, because the importing module anyway can use any convenient name to import a "export default".
- TypeScript: If you use TypeScript, it is easier to apply the
React.FCtype to aconstvariable than to a standard function declaration. - Debugging: In older versions of React,
functiondeclarations provided clearer names in the React DevTools compared to anonymous arrow functions, though modern tooling largely fixes this forconstvariables as well.
Which should you choose?
Most modern React developers prefer const arrow functions for consistency within the component (since hooks and event handlers inside are usually arrow functions), but using the function keyword is still a perfectly valid and standard way to write components.
No comments:
Post a Comment