Search code examples
reactjsmeteorreact-hooks

How does `useTracker` know what to subscribe to?


Going through the Meteor basic tutorial, I am having some issues getting the "task list" to update automatically when I insert an item, so wanted to debug it.

The main app component uses the useTracker function hook to "subscribe" to changes in the TasksCollection:

const tasks = useTracker(() => TasksCollection.find({}).fetch());

return (
  <div>
    <ul>{ tasks.map(task => <Task key={ task._id } task={ task }/>) }</ul>
  </div>
);

I am having a really hard time understanding how useTracker works under the hood.

Isn't the result of fetch() a plain array? How does useTracker know that it needs to subscribe to anything? I doubt that it polls the collection randomly.

I am not sure if this is even related to Meteor, or is it just some React Hooks magic.


Solution

  • You are actually wrong. useTracker doesn't subscribe to anything. You are responsible for subscribing yourself. The only thing useTracker does is connect updates to your collections (a "reactive data-source" in Meteor nomenclature) to a reactive event in react (similar to useState).

    Check your code for a call to Meteor.subscribe('tasks') (or similar).