简体   繁体   中英

Initialize an array in React component render (in terms of performance)

It is known that we should not use anonymous functions in render because they will be re-create on each render. But what about an array of objects like this:

// name props is passed in so it seems like there is a point in initializing the array inside the component
const Component = ({ name }) => {
  // let's imagine there is a lot of large objects
  const bigArray = [{id: 1, name}, {id: 2, name}];

  return <AnotherComponent data={bigArray} />;
}

I suppose that arrays (and objects inside) are stored by reference so when the component is re-rendered, the interpreter sees that this is the same reference and won't re-create the array. Is my assumption correct?

No, it's not the same reference. You're creating new array with new objects inside on each render. If it's completely static, you can extract it from your function to keep the same ref:

const name = 'some-name';
const bigArray = [{id: 1, name}, {id: 2, name}];

const Component = () => (
   <AnotherComponent data={bigArray} />;
);

But in your case this array generated from prop. You can use useMemo() hook to optimize it:

const Component = ({ name }) => (
  const bigArray = useMemo(
    () => [{id: 1, name}, {id: 2, name}],
    [ name ]
  );

   <AnotherComponent data={bigArray} />;
);

Unfortunately when using a React.Component or React.FunctionnalComponent it seems that every single change will re-render the complete array.

We can consider using a React.PureComponent as a workaround of this issue, more infos here: https://codeburst.io/react-array-re-render-performance-ee23f34c5d66

It is better if you move bigArray then (considering it does not change) to a more global state.

// let's imagine there is a lot of large objects
const bigArray = [{id: 1, name}, {id: 2, name}];

// name props is passed in so it seems like there is a point in initializing the array inside the component
const Component = ({ name }) => {
  return <AnotherComponent data={bigArray} />;
}

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