I'd like to make clear one thing.
In React, we often use import {useState, useEffect} from 'react'
.
Can we think of this as a destructuring feature in ES6?
I'd like to make clear one thing.
In React, we often use import {useState, useEffect} from 'react'
.
Can we think of this as a destructuring feature in ES6?
Nope.
It's not like object destructuring but it is actually importing named exports.
To be more clear, it's just importing a module exported as useState
.
No, they are different.
While they look similar (and probably import
was designed to look like destructuring), they don't behave the same way. To set that clear, import
ing uses a slightly different syntax: uses the as
keyword for import renaming instead of the :
familiar from destructuring.
These differences are because of how the module system works. Other differences are:
import
ed variables cannot be assigned to by the importer module, however...
the export
ed variables can be changed anytime by the exporter, and that will also be reflected by the importers' variables, and that implies, that...
it's not possible to nest import renaming, like how it would be possible via destructuring:
import {foo as {bar as baz}} from './module';
//is invalid, as is:
import {foo as {bar: baz}} from './module';
//...while:
const {foo: {bar: baz}} = value;
//is valid.
as the module system is static (like variables), it's not possible to import a dynamic key or use the rest syntax (all imports are known before evaluating the code).
Looking at react src code
export {
useState,
// ...
Children,
// ....
} from './src/React';
so you can import directly from this object e.g.
import { useState } from 'react'
// you can also rename it to anything you want
import { useState as useReactState } from 'react'
or you can get the whole object as exported as default and then reference its useState
import React from 'react'
// use React.useState
// renaming will be like assigning a function to another variable e.g.
const useReactState = React.useState
// you also get all exported types and modules and wrap them up in React name
import * as React from 'react'
Babel transpiled outputs
import React from 'react'
const Component = () => {
const [state, setState] = React.useState()
}
// will transpile to something like
var Component = function Component() {
var _React$useState = _react["default"].useState(),
_React$useState2 = _slicedToArray(_React$useState, 2),
state = _React$useState2[0],
setState = _React$useState2[1];
};
On the other hand
import {useState} from 'react'
const Component = () => {
const [state, setState] = useState()
}
// will transpile to something like
var Component = function Component() {
var _useState = (0, _react.useState)(),
_useState2 = _slicedToArray(_useState, 2),
state = _useState2[0],
setState = _useState2[1];
};
There are some similarities between object destruction and import/export statement, but they are not the same at the end both have their own specific features different with the other