Improve performance on large lists in Vue.js

#VueJS#Web Performance

Hi there! And welcome to the very first VueDose tip! I’m really stocked to start this adventure on VueDose and help devs like you learn some badass tricks.

VueDose’s tips are going to be very concise, and that’s the format I believe people find more useful. So let’s go straight to the point.

Usually we have the need of fetching a list of objects, say users, items, articles, whatever…

And sometimes, we don’t even need to modify them, just to display them or having them in our global state (a.k.a. Vuex). A simple code for fetching that list would be something like:

export default {
  data: () => ({
    users: {}
  }),
  async created() {
    const users = await axios.get("/api/users");
    this.users = users;
  }
};

Vue by default makes reactive every first-level property for each object in the array.

That can be expensive for large arrays of objects. Yeah, sometimes those lists are paginated, but others you just might have that list in the frontend.

That’s usually the case with Google Maps markers, which in fact are huge objects.

So, in these cases, we can gain some performance if we prevent Vue from making reactive that list. And we can do that by using Object.freeze to the list before adding it to the component:

export default {
  data: () => ({
    users: {}
  }),
  async created() {
    const users = await axios.get("/api/users");
    this.users = Object.freeze(users);
  }
};

Keep in mind that the same applies to Vuex:

const mutations = {
  setUsers(state, users) {
    state.users = Object.freeze(users);
  }
};

By the way, if you need to modify the array, you can still do it by creating a new array. For instance, in order to add an item, you can do it in this way:

state.users = Object.freeze([...state.users, user]);

Are you wondering how much is the performance improvement? We’ll see it in the next tip, so stay tuned!

That’s it for today! I hope you like this first tip 😛.

Remember you can read this tip online (with copy/pasteable code) and please share VueDose with all your colleagues if you liked it!

See you next week.

Alex

Do you want to sponsor a VueDose tip? Send an email to info@vuedose.tips and have more info!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.