4

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?

Hasan Haghniya
  • 2,347
  • 4
  • 19
  • 29
xddz9
  • 351
  • 1
  • 5
  • 4
    It’s the exact same thing https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import, it’s just one use destructuring assignment. – Alexander Staroselsky Nov 25 '19 at 06:01

3 Answers3

4

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

mansour lotfi
  • 524
  • 2
  • 7
  • 22
0

Both are the same, import {useState } from 'react' is less verbose and easy for readability and maintenance.

Ajay Ghosh
  • 439
  • 2
  • 11
0

You need React when you want to use JSX.

So if you are doing this in a component where you need to have JSX:

import React from "react";

is the way to go since React already imports the other hooks and its properties. You can simply write is as React.use...

However, if your component (or a custom hook) does not use JSX, then it makes sense to not to import all of React and only the required hooks like useEffect, useState, etc.

import { useEffect, ... } from "react";

I do agree with others about readability but it boils down to personal preference.

Ajay Gupta
  • 1,944
  • 2
  • 21
  • 36