skip to Main Content

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


  1. 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 of u if we plan on not destructing.

    enter image description here

    Here is the babel playground

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. import * as React from "react"
    

    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.

    import { useEffect, useState } from "react"
    

    This imports only the specified members from "react". In this case only the useEffect and useState.

    As a best practice, it’s better to only import what you need.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search