In this article, we discuss what are the differences between named export and default export, which is one of the important interview questions in react js



Alright, let's get started.

1. What are the differences between Named export and default export?

In react js, there are two ways to export a module from a file, those are named export and default export.

Named export

We can have multiple named exports per file. Then import the specific exports they want to be surrounded in braces. The name of the imported module has to be the same as the name of the exported module.

MyComponent.js
export const MyComponent1 = () => {
return(
<h1>Component1</h1>
)
}
export const MyComponent2 = () => {
return(
<h1>Component2</h1>
)
}
Import single named export
import { MyComponent1 } from "./MyComponent";
Import multiple named exports
import { MyComponent1, MyComponent2 } from "./MyComponent";
You can give the different names by using "as"

import { MyComponent2 as MyNewComponent } from "./MyComponent";
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.

Default export

You have only one default export per file. When we import we have to specify a name and import like:

import MyComponent from "./MyComponent";
const MyComponent = () => {
return(
<h1>Welcome</h1>
)
}
export default MyComponent;
The naming of import is completely independent in default export and we can use any name we like, below is an example
import AnyName from "./MyComponent";
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object, or anything else. This value is to be considered as the “main” exported value since it will be the simplest to import.