I see this code pattern a lot in React code:
render() {
const units = this.props.units;
const temperature = this.state.temperature;
return (<p>{temperature} {units}</p>);
}
and some developers I've asked say that its standard practice to pull state/props into local constants before using them in render or other functions - however, I can't find this practice discussed anywhere in the React docs, and the example code in those docs sometimes just access state/prop attributes directly.
I would prefer to use direct access because it makes the code more readable when you can immediately see where attributes are coming from instead of having to hunt down the local constant definitions.
Before I make this decision though, I was wondering if anyone knew why this practice exists and if there are good reasons to use it?
Is there a functional difference between the example above and this?
render() {
return (<p>{this.state.temperature} {this.props.units}</p>);
}
Its a standard practice to pull state/props when there a MANY props/state that are going to be used inside your functions
eg: const { prop1, prop2, prop3, prop4, ... } = this.props
const { state1, state2, state3, ... } = this.state
You can now reference them with the const names instead of
this.props.propName/stateName everywhere.
You shouldn't do that in the example you provided where there is just 1/few props/state
const units = this.props.units; // Not recommended
Bottomline : Just cleaner code. Matter of preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With