[React] When Should You Use Brackets With Imports?

Even if you’ve used React for a while, you might not know why you need to import certain things with curly braces, and not others.

For example, if you use hooks, a common importing statement that you may use is:

import React, { useState } from "react";

The reason that you don’t need to use curly braces around “React” here is because it’s the default module exported by “react”.

In fact, you could change “React” in the above line to anything you wanted and it would still refer to the same core “react” function.

On the other hand, “useState” is a specific function that has to be exported by name. And since it’s not the default export, you need to use curly braces.

I’ll go over a few more examples to make this crystal clear for you.

For the rest of this post, imagine you’re importing from this file - ModuleComponent.js:

Non-Bracket Imports Refer to The Default Exports

In ModuleComponent.js, the function `A` is exported by default.

Whenever something is imported from this file without braces, it will refer to function `A`.

What’s really interesting is that even if you use the name of another function, it will still refer to the default export.

In this case, importing “B” without braces will still refer to function `A`.

Curly Braces Let You Import Non-Default Exports

If you want access to a non-default object in a module, you have to use curly braces, and use the exact name of the object.

Here’s how you could import module `B`:

Note that you could also import `B` on the same line as `A`, just separated by a comma.