Difference Between Named Exports and Default Exports in React
Mastering Module Export Patterns
Table of contents
If you are using React, you already know that there are two different exports, one uses the default tag, and the other doesn’t.
But why it’s so? These two exports have different use cases which will be explained later in this article.
But firstly, let’s find out what these two exports are called:
• Exports with the default tag are called Default exports.
• Exports without the default tag are called Named exports.
These exports are not React features but rather ES6 features, although they are very common in React projects.
Default Exports
Default exports are created by including a default tag in the exports.
You can define default export at the bottom of the file:
Or you can define it when declaring your component:
Only one default export is allowable in a module:
The best practice to use default export would be when the exported component is only imported once or when the file only has one export.
When importing default export, you can name it whatever you like (make it relevant) and you don’t need to use brackets, not like with named exports, which we will talk about in the next section:
Named Exports
Named exports are created without default tag and as well can be defined at the bottom of the file:
Or at the top when you are declaring the component, which is a more common practice:
Many named exports are allowed in file at once, some can be exported and some not:
Named exports should be used for components that will be used many times, for example, helper function modules.
When importing named exports, the name must be in the brackets and the same as in export:
Although named export can be renamed using alias:
Conclusion
Although named exports and default exports have different use cases, a wrongly chosen export won’t break your code.
But it’s great to follow best practices.
This way your code becomes more readable and consistent.