Just a curiosity and I couldn't find an answer to it on SO. Does it matter where I place a variable/dataset in respect to a react component? To clarify, the dataset is going to be only used in that component. If it does matter, I'm wondering if it has to do with performance or it's just a convention/good practice kind of thing.
import React from 'react'
export const Component: React.FC = () => {
const dataSet: string[] = [...]
return (
<div className='work-experiences'>
</div>
)
}
VS.
import React from 'react'
const dataSet: string[] = [...]
export const Component: React.FC = () => {
return (
<div className='work-experiences'>
</div>
)
}
CodePudding user response:
It can matter. In your examples, you're recreating the array every time the component function is called in the first code bloc, but creating it just once and then reusing it in the second code block. That means:
- If the data in the array is unvarying, that's extra unnecessary work in your first example. (It's unlikely to matter in lots of cases, but in a few cases where performance is particularly important, it will.)
- If the data is varying, it should be local to the component but should probably be in state, not recreated every time.