Search code examples
javascriptecmascript-6es6-modulesdestructuring

Is `import { useState } from 'react'` kind of destructure or not?


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?


Solution

  • 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

    ES6 in-depth | Export Statement | Import Statement