8


I am creating a new Vue 3 project and i saw many people online declaring refs like this.
const myVariable = ref(false)

Why are we using const all of a sudden in Vue 3?
I get that refs wrap them in some way to make them editable but i still don't get why not declaring them like this:
let myVariable = ref(false)

I know it may sound a foolish question for Vue 3 devs but i cannot understand the reason behind changing values to constants.

During the meanwhile i am using the const declaration in composition API but i'd like to acknowledgwe the reason behind

1 Answer 1

6

it's preferences but the argument why const is used is when the value is not changing e.g:

const name = 'John';

// Shouldn't work.
name = 'Bill';

With ref(), you don't replace the variable but the property

const name = ref('John');

name.current = 'Bill';

Here's how eslint explains it:

If a variable is never reassigned, using the const declaration is better.

const declaration tells readers, “this variable is never reassigned,” reducing cognitive load and improving maintainability.

Docs (at the time of writing): https://eslint.org/docs/latest/rules/prefer-const

2
  • Thanks for the answer! Do you know when people should use let in combination with ref()?
    – Ivan_OFF
    Commented Nov 23, 2022 at 14:08
  • 1
    i never experienced one so i really can't tell. if you want to use let then it shouldn't cause any problem. you can try re-assigning the value and see what happens. i believe it won't react to the change because Vue track changes of object property, not variable. that's just not possible at all in javascript even. See vuejs.org/guide/extras/… Commented Nov 23, 2022 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.