Search code examples
reactjstypescript

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.

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