const or let in React component

const vs let is mostly to do with "changing" in a code block. It only matters in situations like this:

const myValues = this.props.someData;
if (*some condition*) {
  myValues = [];
}

In this situation you would need to use let because you are changing the value assigned to the variable myValues:

let myValues = this.props.someData;
if (*some condition*) {
  myValues = [];
}

If props.someData is changing it will trigger a re-render of the component. So const vs let does not come in to play. The entire render method is re-run.

So that said, I use const in the situations you are describing. Unless you are directly manipulating the valuable of a variable, use const.


const is a signal that the variable won’t be reassigned.

let is a signal that the variable may be reassigned

Additional things to ponder:

  • Use const by default
  • Use let only if rebinding is needed
  • const does not indicate that a value is ‘constant’ or immutable.

    const foo = {};
    foo.bar = 10;
    console.log(foo.bar); // --> 10
    

    Only the binding is immutable. ie using an assignment operator or a unary or postfix -- or ++ operator on a const variable throws a TypeError exception

  • ES6 const and let are hoisted too. Although the identifiers has the same memory reference from compile time, they cannot be accessed before declaration in the code. (but not as we thought the declaration would be physically moved to the top in the scope) ;)