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.
Is there any difference between the two? (Maybe a performance difference?) Is there any reason to prefer one over the other?
3
Answers
Question is not specific to react, but any ES module where we can either destructure imports or use dot notation.
Might be a slightly better to extract the property once instead of reading it from the object.
Also, the fact that the minified bundle will include something of the form
r.u
instead ofu
if we plan on not destructing.Here is the babel playground
There is no difference. There in no performance difference or functionality difference. In fact they both reference the same exact function.
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 entireReact
object. But if youimport { useState } from 'react'
, then the bundle may be able to include only theuseState
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.
This imports all the exported members from "react" and bundle them into a single object called ‘React’ in your case. This could lead to a larger bundle size since it imports all the exports. If you’re using many members, this way is convenient.
This imports only the specified members from "react". In this case only the
useEffect
anduseState
.As a best practice, it’s better to only import what you need.