简体   繁体   中英

Does it make sense to memoize large array operations in React?

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])
}

Yes, but more importantly, 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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM