xddz9
xddz9

Reputation: 381

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?

Upvotes: 4

Views: 1893

Answers (3)

Ajay Gupta
Ajay Gupta

Reputation: 2033

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.

Upvotes: 0

mansour lotfi
mansour lotfi

Reputation: 602

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

Upvotes: 5

Ajay Ghosh
Ajay Ghosh

Reputation: 439

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

Upvotes: 0

Related Questions