Reputation: 31
I have some doubts regarding performance when a functional component has inner functions.
When having a functional component with an inner function, does that inner function get re-created over and over again on every render?
In that case, if I was to memoize the component with React.memo()
, would that function be memoized as well?
Here's a dummy example of what I'm referring to:
const MyComponent = React.memo(({genre, name}) => {
const someFunction = genre => {
return (genre === 'male') ? 'Mr.' : 'Ms.';
}
return (
<h1>Hello {someFunction(genre)} {name}!</h1>
);
});
Upvotes: 3
Views: 688
Reputation: 12691
From the react Hooks docs :
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. [...]
Traditionally, performance concerns around inline functions in React have been related to how passing new callbacks on each render breaks shouldComponentUpdate optimizations in child components. Hooks approach this problem from three sides.
The useCallback Hook lets you keep the same callback reference between re-renders so that shouldComponentUpdate continues to work:
The useMemo Hook makes it easier to control when individual children update, reducing the need for pure components.
Finally, the useReducer Hook reduces the need to pass callbacks deeply, as explained below.
Read more here.
Also in your example, you can put the inner function outside the function component, because it does not use anything from inside the component, like this :
const someFunction = genre => {
return (genre === 'male') ? 'Mr.' : 'Ms.';
}
const MyComponent = React.memo(({genre, name}) => {
return (
<h1>Hello {someFunction(genre)} {name}!</h1>
);
});
Upvotes: 4