Reputation: 74
I have a query regarding something i saw multiple times in the react docs.
They use a constant in render method which stores the value of something from the state and then use the const for further logic.
Eg ->
render(){
// showLogin is boolean
const showLogin = this.state.showLogin
showLogin ? return(something) : return(something else)
}
So my question is why not directly use this.state.showLogin and why create a separate const?
Is there any benefit of using this way or is it just done for no reason as such.
Documentation for example -> https://reactjs.org/docs/conditional-rendering.html
Upvotes: 0
Views: 115
Reputation: 980
might be the careless typing. but your question has some issues. the ternary operator has an advantage over conventional if-else, it can return value by default.
const color = true ? 'orange' : 'green';
coming to your question,
render(){
const { showLogin } = this.state;
return (
<div>
{showLogin ? <Component1 /> : <Component2 />}
</div>
)
}
//
render() {
const { showLogin } = this.state;
if (showLogin) {
return <Component1 />
} else {
return <Component2 />
}
}
and to the answer, the reasonable answer i can think of is two,
also as others mentioned readability and of course it is the shorter syntax.
following lines does the same (of course there is functional difference, the first is destructuring from the state object. the second is assigning to a variable), so no worries..
const { showLogin } = this.state;
const showLogin = this.state.showLogin
Upvotes: 1
Reputation: 6057
It's because of the readability. You will also found object destructuring
in some cases.
like const {showLogin, otherProperty} = this.state;
It just improves the readability of your code.
Upvotes: 0
Reputation: 2549
Your code
render(){
// showLogin is boolean
const showLogin = this.state.showLogin
showLogin ? return(something) : return(something else)
}
does the same thing as
render(){
// this.state.showLogin is boolean
this.state.showLogin ? return(something) : return(something else)
}
The difference is not the logic of the code, the difference is readability.
Upvotes: 0
Reputation: 387
In this example it is purely for cleaner and more readable code. If they would use:
this.state.showLogin ? return(something) : return(something else)
there will be no difference for the machine, but imagine a real code base with many lines of codes and many state values (showLogin, toggleBar, hideNotification etc). the code will get messy really quickly. So out of caring for next developer (and for your future self), its better to write code as clean as possible.
And regarding CONST -> if the variable wont be reassigned in the future you sould always use const instead of let.
Upvotes: 1