ReactEasy

Difference between default and named exports?

A module can have one default export, imported with any name (import Card from "./Card"), and any number of named exports, imported by their exact names in braces (import { Card, CardTitle } from "./Card"). Both are standard JavaScript modules, not React-specific.

Default export

  • export default function Card() {}.
  • Import with any name: import Whatever from "./Card".
  • Required by some conventions: Next.js page.tsx and layout.tsx, React.lazy(() => import("./Chart")) expects a default export.

Named exports

  • export function Card() {}, export const CardTitle = ....
  • Import with the same name, or rename: import { Card as BaseCard } from "./Card".
  • Many per file, good for related pieces and utilities.

Why many teams prefer named exports

  • Consistent names across the codebase, making search and refactoring easier.
  • Better autocomplete and automatic imports.
  • Typos fail at build time instead of silently importing the default under a wrong name.
  • Tree shaking works for both, but barrel files with many named re-exports need care.

Mixing

A file can have both: export default Card; export { CardTitle };, imported as import Card, { CardTitle } from "./Card".

Lazy loading named exports

lazy(() => import("./Chart").then((m) => ({ default: m.Chart }))).

Code example

tsx
1// components/card.tsx
2export default function Card({ children }: { children: React.ReactNode }) {
3 return <div className="card">{children}</div>;
4}
5
6export function CardTitle({ text }: { text: string }) {
7 return <h3>{text}</h3>;
8}
9
10export const CARD_PADDING = 16;
11
12// app.tsx
13// import Card, { CardTitle, CARD_PADDING } from "./components/card"; // default + named
14// import Panel from "./components/card"; // any name for the default
15// import { CardTitle as Title } from "./components/card"; // rename a named export
16
17// Lazy loading a named export
18import { lazy } from "react";
19export const LazyTitle = lazy(() =>
20 import("./components/card").then((m) => ({ default: m.CardTitle }))
21);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app