Fine-grained User Reactivity in Meteor

Setting the fields when using collection.find and collection.findOne is very important. This is from the Meteor docs.

Note that when fields are specified, only changes to the included fields will trigger callbacks inobserve, observeChanges and invalidations in reactive computations using this cursor. Careful use of fields allows for more fine-grained reactivity for computations that don’t depend on an entire document.

One place where this isn’t obvious is Meteor.user().

Meteor.user()

is the same as

Meteor.users.findOne(Meteor.userId())

Meteor.user() returns the whole user object.

Template.test.helpers({
username: function() {
return Meteor.user().username;
}
});

The above works but it’s bad because anytime any attribute of Meteor.user() changes the template will re-run. The below example is a better way of doing it.

Template.test.helpers({
username: function() {
var user = Meteor.users.findOne(Meteor.userId(), {fields: {username:1}});
if (user) {
return user.username;
}
}
});

Now the template will only re-run if Meteor.user().username changes.

Show your support

Clapping shows how much you appreciated Dominus’s story.