Why do so many programmers imports `useState` separately, whereas it would be just as workable to simply use `React.useState`?

Viewed 327

I am curious as to why so many programmers import useState separately.

import React, { useState } from 'react';
const [foo, setFoo] = useState('foo');

Whereas, wouldn't it be easier on the memory to just import react and do React.useState?

import React from 'react';
const [foo, setFoo] = React.useState('foo');
3 Answers

Some of us have different preferences. It's tab vs spaces basically. I like to use React.use wherever the hooks are. So if I were to delete the hook from the file, I could do it in that line and should not worry about the unused imports.

When I'm prototyping, I use React.useState because it's quicker to type without having to wait for the IDE to auto import for me. Later on if I have more time and know that the code won't change much anymore, I may refactor to use useState or useEffect because it looks cleaner

Also when I write reusable hooks, I will use useHook separately because it looks simpler and I know that I won't touch the code for a while.

Destructuring is one of good features in ES6 syntax comparing with vanilla Javascript. It makes code more short, clean and readable. And many developers are following this updated feature in ES6 in coding.

In React programming, developers enjoy writing code with Desructuring feature rather than referring sub property with parent object.

So I'd like to say Destructuring has became one common rule in perspective of code formatting in most Javascript programming.

And this Destructuring feature is widely used in exporting and importing modules in javascript.

So to unify coding pattern in whole project, developers are choosing choice to import useState directly from react.

As well, in most cases, we use several states in React component which means that we need to use useState multiply. So it will also reduce repetition of using "React".

Here is article which would be helpful for you.

Related