When using hooks for state, effect, context, etc, I do this:
import React, { useState, useEffect, useContext } from 'react';
However, I noticed that the following works just fine:
import React from 'react';
const App = () => {
const [counter, setCounter] = React.useState();
React.useEffect(() => console.log('hello!'), []);
}
My question is, is there any difference between those two? Maybe when it comes to bundle size, or is Webpack smart enough to handle that?
Otherwise, is that bad practice? Which approach do you use, and why?
its better to use import {useState } from 'react'
just because of readability , less typing and clean coding . it doesn't matter in performance and bundle size
两者都是一样的, import {useState } from 'react'
不那么冗长,易于阅读和维护。
This thing is called destructuring in JS. You can specify what fields of an object do you need to spread in separate variables:
const PI = Math.PI.
is the same as
const {PI} = Math;
Which means, that here you import several fields of React object:
import { useState, useEffect, useContext } from 'react'
I suggest you to use destructing, since this way you import only the parts of the object that you need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.