Topic 7 of 54
Importing & Exporting
Overview
As your app grows, you can't keep all components in one file. You need to split them into separate files. ES6 Modules (import and export) allow you to share these components across your project. Understanding Default vs Named exports is crucial for keeping your file structure organized.
Syntax
Use Default exports when a file contains only one main component. It makes importing cleaner.
One per file
jsx
// --- Button.jsx ---
function Button() {
return <button>Click</button>;
}
export default Button; // Exporting
// --- App.jsx ---
// Importing (You can name it whatever you want, though keeping it the same is best practice)
import Button from './Button';
import MyCustomButton from './Button'; // Also works!Use Named exports when a file exports multiple utility functions or sub-components. You must import them using their exact names.
Multiple per file
jsx
// --- Typography.jsx ---
export function Heading() { return <h1>Heading</h1>; }
export function Paragraph() { return <p>Text</p>; }
// --- App.jsx ---
// Must use exact names wrapped in curly braces {}
import { Heading, Paragraph } from './Typography';Common Pitfalls
- Forgetting the curly braces `{}` when importing a Named export.
- Trying to use `export default` twice in the same file. A file can only have one default export.
Interview Tips
- Many modern teams strictly use Named Exports for everything because it forces consistent naming across the entire codebase and prevents confusing rename bugs.
Real-World Example
Grouping related UI components into a single file and exporting them using Named exports.
example
jsx
// UIComponents.jsx
export function Card() { return <div className="card">...</div>; }
export function Avatar() { return <img className="avatar" />; }
export function Divider() { return <hr className="divider" />; }
// Dashboard.jsx
import { Card, Avatar } from './UIComponents';
function Dashboard() {
return (
<Card>
<Avatar />
<h2>User Dashboard</h2>
</Card>
);
}