In JavaScript modules (and therefore React), components and functions can be exported in two ways — Default Exports and Named Exports. Understanding their difference is crucial for writing maintainable and scalable React code.
A module can have only one default export. It’s imported without curly braces, and the importing name can be anything. Default exports are ideal for modules exporting a single main component or function.
// Button.js - Exporting a component as default
export default function Button() {
return <button>Click Me</button>;
}
// Importing in another file
import Button from "./Button"; // ✅ Works
import MyBtn from "./Button"; // ✅ Works (name can be changed)
Named exports allow multiple items to be exported from a single file. They must be imported using the same name within curly braces. Named exports are best when a module contains multiple related utilities or components.
// utils.js - Exporting multiple functions
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
// Importing specific functions
import { add, subtract } from "./utils"; // ✅ Must match names
| Aspect | Default Export | Named Export |
|---|---|---|
| Quantity per file | Only one allowed | Multiple allowed |
| Import syntax | No curly braces | Requires curly braces |
| Import name flexibility | Can rename freely | Must match exported name |
| Use case | Single component per file | Utility or constants module |
| Example | export default App |
export const Button |
Combining default and named exports through an index.js file helps organize large projects and simplifies imports.
// components/index.js - Aggregating exports
export { default as Button } from "./Button";
export { default as Header } from "./Header";
export const VERSION = "1.0";
// Import elsewhere using named imports
import { Button, Header, VERSION } from "./components";
Switch between modes to see how the syntax changes for both the exporting and importing files.
export default function Profile() { ... }
import AnyName from "./Profile";
App, Navbar).MathUtils.js file and export multiple functions using named exports.Button.js file with a default export component.App.js to practice mixed imports.Goal: Learn when and how to use default vs named exports for better modular design in React.