I am currently studying React with TypeScript and have come across two different ways to export a default function component. Here are the two examples:
- Exporting the function separately:
function PriceListPage() {
return (<></>);
}
export default PriceListPage;
- Exporting the function directly during declaration:
export default function PriceListPage() {
return (<></>);
}
Both seem to work the same way, and I haven’t noticed any technical differences in behavior.
My questions are:
- Are there any technical differences between these two approaches?
- Are there any best practices, conventions, or recommendations from the React or TypeScript community that favor one style over the other?
I am the Full Stack Software Engineer of a new upcoming large single page frontend project and have decided to use React with TypeScript. As part of setting up code styling with best practices, I’d like to know if there are also any practical differences between these styles, and if one should be preferred for maintainability.
Any insights into which method is more commonly used or why one might be preferred would be greatly appreciated!
2
Answers
There are no technical differences between the two.
When it comes to best practices, it depends on your team’s conventions, but I think that typically the best practice is to not use default exports at all, use instead
The problem with default exports is that it’s too easy to rename them, which makes the code harder to understand if the same component is called differently in different files. Named exports can be renamed too if necessary, but at least the import line is much more explicit about the renaming, so it’s harder to do it by accident.
There is no underhood abstractions or technical differences between default or name exports.
Advantages of Named Exports:
Named exports are useful when you need to export several variables,
functions, utils, components, expressions.
We can have same name usage of components when use import them. When importing this module, named exports must be referred to by the exact same name (optionally renaming it with as).
Advantages of Default Exports:
When to Use Default Exports:
function.
References: More about imports and exports