Vue Tip: Avoid Side Effects in Computed Properties
It is considered bad practice to introduce side effects inside computed properties and functions because it makes the code unpredictable and hard to understand.
What is a side effect? In the context of computed properties, a side effect is a modification of the state's global state or the internal component state.
Let's take a look at an example with side effects:
Now let's change the code and remove the side effects:
Now the code is predictable and easy to understand. The computed properties fullName
and reversedArray
only depend on the values of firstName
, lastName
, and array
. They don't modify the global state or the internal component state.
Recommended Reading
Read this fantastic article from Michael Thiessen for more details about side effects.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Test Vue Components Using Vue Testing Library
Vue Testing Library is my preferred Vue.js testing library that encourages good testing practices.
Vue Tip: Typing Template Refs With TypeScript
Template refs only exist after the component is mounted. Thus, it’s necessary to type template refs with a union type that includes the DOM element type as well as null.