I often wrote functional components following a 'Class architecture' where all my function that concern the component are written inside of it like a method in a class.
For example, I have here a function counterAsFloat that is related to the Counter component. As you see I just wrote it inside of the component:
export default function Counter() {
const [counter, setCounter] = React.useState(0);
const counterAsFloat = () => {
return counter.toFixed(2);
};
return (
<div className="counter">
<h1>{counterAsFloat()}</h1>
<button onClick={() => setCounter(counter + 1)}>
Increment
</button>
</div>
);
}
But actually I could also just declare the function outside the component and use it with a parameter:
const counterAsFloat = (counter) => {
return counter.toFixed(2);
};
export default function Counter() {
const [counter, setCounter] = React.useState(0);
return (
<div className="counter">
<h1>{counterAsFloat(counter)}</h1>
<button onClick={() => setCounter(counter + 1)}>
Increment
</button>
</div>
);
}
So are there any pros or cons to write the functions outside the functional 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>
);
}