Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript The Provider and Consumer Solution

Norman Lew
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Norman Lew
Full Stack JavaScript Techdegree Graduate 14,784 Points

Why are brackets used in the import statement: import { Consumer } from './Context';

Why are brackets used in the import statement: import { Consumer } from './Context';

1 Answer

Hey Norman. This syntax is called destructuring and it's a new feature that comes with ES6. I'll first explain what destructuring is, and then explain the use of it in importing.

Destructuring allows you to get a specific property out of an object easily. Consider this code:

const myObj = {
  name: "Norman"
}

To get the name property from the object you could use dot notation:

const name = myObj.name;

Or you could use this syntax:

const { name } = myObj;

I know this looks a bit confusing, but it can be really useful. You can also use destructuring with arrays, but instead of going deep into destructuring in my answer I am going to highly recommend you take the course Introducing ES2015. Destructuring is covered in a lot of detail there, as well as a lot of other super cool ES6 features that will make you a better programmer and make it easier for you to learn modern JavaScript tools and frameworks.

In the context of importing a package, you may only want to import a specific component of that package. When you're using React for instance, you often use the Component module that comes with React. Component is a property of the React object, so you can import it using import { Component } from 'react';.

Strictly speaking, destructuring doesn't always have any benefit over dot notation, but it is a cleaner more modern syntax, and there are times when it's faster. Destructuring does make working with data in arrays a lot easier.

To understand the import keyword better, have a look over the documentation for it.

Good luck and I hope this was helpful!