Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a difference between: e.g. useEffect() & React.useEffect()

I recently came across this:

React.useEffect(() => {}, []);

I’m used to importing useEffect and calling it like this:

useEffect(() => {}, []);

which in my experience seems to be more common.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any difference between the two? (Maybe a performance difference?) Is there any reason to prefer one over the other?

>Solution :

There is no difference. There in no performance difference or functionality difference. In fact they both reference the same exact function.

import React, { useEffect } from 'react'
React.useEffect === useEffect // true

So which to use is entirely down to your preferences.

Some people like to have an namespace for React stuff so you can type React.use and have your IDE’s autocomplete give you nice suggestions.

Some people like to keep line length shorter by importing the functions directly.

It’s up to you. Neither is obviously wrong.


One thing that maybe matters is that a smart bundler may be able to tree shake things you aren’t using, which makes the code you are shipping to the user smaller.

If you do import React from 'react'; React.useState() then the bundler must include the entire React object. But if you import { useState } from 'react', then the bundle may be able to include only the useState function in the final bundle.

I say may because bundling is complicated. And not all modules that you import may be tree shaken in this way. And for React, you probably are including all of React in your bundle anyway.

But for these reasons, I’d argue it’s a reasonable habit to get into when the module you are importing supports it.


And for what it’s worth, the react docs import each function individually.

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading