简体   繁体   中英

Is react useMemo more performant than module level variable?

I need to hard-code some data (no need to change) for a react component, just wondering how i can do it in the most performant way. By performant, i mean fast execution as well as minimum usage of system resource. Two ways I have:

// Way 1. define data outside the component
const data = ['test1', 'test2', 'test3', 'test4', 'test5'...'test1000']

export default function TestComponent() {
  return <>{data.map(item => <p>{item}</p>)}</>
}

// Way 2. define data inside the component with useMemo
export default function TestComponent() {
  const data = useMemo(() => ['test1', 'test2', 'test3', 'test4', 'test5'...'test1000'], [])
  return <>{data.map(item => <p>{item}</p>)}</>
}

Just want some advice on which of the above (or even other ways) is more performant. Thanks!

The most performant approach will be to not do any computation inside the component - just return the same constant value every time:

const data = ['test1', 'test2', 'test3', 'test4', 'test5'...'test1000']
const result = <>{data.map(item => <p>{item}</p>)}</>
export default function TestComponent() {
  return result
}

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