Functional Component: Write functions inside or outside the component?
This question is pretty opinion-based but there are few notes that you need to think about.
Declaring the function outside of scope is foremost for readability and reusability.
// Reuse logic in other components
const counterAsFloat = (counter) => {
return counter.toFixed(2);
};
// If Counter has complex logic, you sometimes want to compose it
// from functions to make it more readable.
export default function Counter() {
...
return (...);
}
One can argue that the first option is less performant because you declare the function on every render:
export default function Counter() {
...
// declare the function on every render
const counterAsFloat = () => {
return counter.toFixed(2);
};
return (...);
}
Such case is premature optimization. Check out JavaScript closures performance which relates to this.
Note that in this specific case, inlining the function is much better approach.
export default function Counter() {
...
return (
<div>
<h1>{counter.toFixed(2)}</h1>
...
</div>
);
}