Vue Tip: Avoid Side Effects in Computed Properties

Michael Hoffmann
Aug 25, 2022
| 1 min read
| 132 views
Michael Hoffmann
Aug 25, 2022
1 min read
| 132 views
Script

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:
Bad
<script setup lang="ts">import { computed, ref } from 'vue'const firstName = ref('Michael')const lastName = ref('Hoffmann')const array = ref([])const fullName = computed(() => { firstName.value = 'Mike' // side effect return `${firstName.value} ${lastName.value}`})const reversedArray = computed(() => array.value.reverse()) // side effect, original array is mutated</script>
Now let's change the code and remove the side effects:
Good
<script setup lang="ts">import { computed, ref } from 'vue'const firstName = ref('Michael')const lastName = ref('Hoffmann')const array = ref([])const fullName = computed(() => `${firstName.value} ${lastName.value}`)const reversedArray = computed(() => array.value.slice(0).reverse()) // .slice creates a copy of the array</script>
Read this fantastic article from Michael Thiessen for more details about side effects.
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.
Vue Tip: Test Vue Components Using Vue Testing LibraryAug 19, 2022
Vue Tip: Typing Template Refs With TypeScriptSep 3, 2022
Show comments