2

I often see the following pattern used within JavaScript classes and React.

class Welcome extends React.Component {
  state: {
   someValue: 1
  }

  render() {
    const myValue = this.state.someValue;

    return <h1>Hello, {myValue}</h1>;
  }
}

My question is, what is the point/benefit of declaring state to a variable before the return when you can access the value with this.state.someValue within return anyway?

1 Answers1

2

The benefit of assigning to a variable or destructuring comes when you are using the same variable multiple times you multiple variables from array in which case you don't need to write this.state again and again.

In the above case you could simply use the value from state and there isn't any benefit to assignment before using.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400