Reputation: 23553
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?
Upvotes: 10
Views: 3488
Reputation: 143
The approved answer isn't fully correct. There is one really important distinction about this sentence:
Another note: useCallback will not avoid recreating functions (you still pass a new function into useCallback too).
The function you pass to useCallback is returned every render. This means you have the same function, assuming the dependencies you defined haven't changed.
As an exercise to the reader define a function inside of a useCallback and store that result into a variable and then in a useEffect have that variable be the sole dependency. The useEffect will not re-run bc it's the same reference (strict equality.)
Upvotes: 2
Reputation: 2517
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.
Upvotes: 12