Let's say I have a component:
export const MyComponent = ({largeArray}) => {
const arrayINeed = largeArray.sort()
}
From what I understand, largeArray.sort() will be called every time MyComponent re-renders, if largeArray is huge, doesn't that raise some degree of performance concerns?
Is it better in this case to memoize the result like this?:
export const MyComponent = ({largeArray}) => {
const sortedArray = useMemo(() => largeArray.sort(), [largeArray])
}
CodePudding user response:
Yes. It's also important to recognize that you are mutating the array passed in props by calling its sort method. Instead, spread the array into a new array and sort the new array:
import {useMemo} from 'react';
export const MyComponent = ({largeArray}) => {
const sortedArray = useMemo(() => [...largeArray].sort(), [largeArray]);
}
