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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With