Prefer Named Functions Declarations for Components
Today, I offer a simple recommendation:
Prefer named function declarations for component descriptions
As developers, we edit, debug, extend, and refactor existing code WAY more often than we create new code. So I prefer “code style” that keeps change to a minimum.
Why named function declarations are great for components
There are four things that make named function declarations a perfect fit for describing components.
Debugging. Named functions tell React how to tailor error messaging in the console and React Dev Tools.
Adding Hooks. Function declarations have a required function block and return. This block and return are required for any component using React Hooks. So, while arrow function expressions may “look cleaner” (without Hooks), they require more code motion to utilize Hooks.
Hoisting. Function declarations are automatically hoisted. Function declarations are available anywhere, indifferent to where the function resides in a file (top, bottom, middle).
Diffs. When changing a component from implicit returns to explicit return (to use Hooks), the indentation is effected. In a git diff, it now it looks like the whole component changed. Defaulting to a syntax with an explicit return keeps diffs clear and legible.
Take it home
Check out this CodeSandbox. It illustrations all the common ways you can create a component.
What’s your preference?
What good or bad experiences reinforced that preferences? Do you agree or disagree with my reasons? Do you have any exceptions I should should be considering?