I found a similar discussion to my question here but wanted to dig deeper.
I have yet to find any React documentation that discusses whether static variables (that are unchanging but need to be used for a React view) should be stored as a state variable or be rebuilt each time the component is rerendered.
Let's say that I have a React component that takes in a prop, which is a list, and I want to map this list to a certain output. In my use case I am turning the list into the format for the options my component's select picker will use. Once this list is made, it does not need to change. All options will remain the same for the rest of the component's use.
It feels weird to throw it into state, although it just seems more efficient. Let's go through two approaches.
Approach #1: Store option list in component state.
class Component extends React.Component {
constructor(props) {
this.state = {
options: props.list.map(some => computation)
}
}
render() {
return ( <SelectPicker options={this.state.options} /> )
}
}
Approach #2: Recreate variable upon each rerender.
class Component extends React.Component {
constructor(props) {
...
}
render() {
const options = this.props.list.map(some => computation)
return ( <SelectPicker options={options} /> )
}
}
The latter seems more correct, in that since the options array is never meant to change, it is only meant to be initialized once, and it doesn't make sense to put a watcher on it for being part of state
. The former just seems more efficient, as we only compute this value once, rather than recomputing it every single time the component is rerendered. Yes React will compare the state between rerenders, but won't it compare the options
list references? Whereas the latter example will completely rebuild a new list? Tbh, neither of these seem like the "clean" approaches to this.