[JS Tip] When to Use Different Import Styles

October 10, 2024

In JavaScript/TypeScript, you'll often see different import styles like these.

import "@/app/ui/global.css";
import { inter } from "@/app/ui/fonts";
import React from "react";
// or
import React, { useState, useEffect } from "react";

Ever wondered why there are different import styles?


1. Side effects (like CSS or polyfills)

import "@/app/ui/global.css";

This style is for side effects, like importing stylesheets or modules that run code upon import without exporting anything.

2. Named exports

import { inter } from "@/app/ui/fonts";

This is an import of a named export. You use destructuring when you want to import specific exports from a module, rather than importing the whole module.

3. Default exports

import React from "react";

This imports the default export of the module. Every module can optionally define one default export, which you import without using {}.

4. Both named and default exports

import React, { useState, useEffect } from "react";

This imports the default export (React) along with specific named exports (useState and useEffect). Default exports aren’t destructured, while named exports are.

Hope this little tip helps. Happy coding! Happy coding!