Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference from putting function outside of React component?

Tags:

reactjs

I know that it's going to be small, but is there a performance difference if you put functions outside of a React component?

Eg version 1:

const handleFetch = () => {
    // Make API call
}

const MyComponent = () => {
    useEffect(()=>{
        handleFetch();
    })
    return(<p>hi</p>)
}

Vs version 2:

const MyComponent = () => {
    const handleFetch = () => {
        // Make API call
    }

    useEffect(()=>{
        handleFetch();
    })
    return(<p>hi</p>)
}

In version 1 would handleFetch not be recreated when MyComponent re-renders?

like image 793
Evanss Avatar asked Mar 12 '20 19:03

Evanss


1 Answers

is there a performance difference if you put functions outside of a React component?

Yes but you will likely never run into a noticeable performance downgrade of deciding to define a function inside a component. Almost always, the rest of your application's performance will overshadow the cost of putting functions in your components. Quoted from React's FAQ regarding functions defined in functional components in general:

Are Hooks slow because of creating functions in render?

No. In modern browsers, the raw performance of closures compared to classes doesn’t differ significantly except in extreme scenarios.

https://reactjs.org/docs/hooks-faq.html#are-hooks-slow-because-of-creating-functions-in-render

In version 1 would handleFetch not be recreated when MyComponent re-renders?

No, it will not be recreated because handleFetch is defined outside of the functional component. It's only in version 2 handleFetch will be recreated when MyComponent re-renders.

Another note: useCallback will not avoid recreating functions (you still pass a new function into useCallback too).

As a general rule for me, define the function inside the component first then extract it if it's not a hassle or it can be reused among multiple components. Sometimes, when I do extract it, I find I need to add 2 or more extra parameters to pass variables from my component to the function. But if I left it inside the functional component, I wouldn't need any parameters.

like image 171
kmui2 Avatar answered Nov 15 '22 07:11

kmui2