Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I import useState and useEffect or is it ok to use React.useState and React.useEffect?

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?

like image 592
xddz9 Avatar asked Oct 14 '25 18:10

xddz9


2 Answers

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

like image 125
mansour lotfi Avatar answered Oct 17 '25 07:10

mansour lotfi


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.

like image 43
Ajay Avatar answered Oct 17 '25 09:10

Ajay