react-meteor-data

v2.7.1Published last year

react-meteor-data

This package provides an integration between React and Tracker, Meteor's reactive data system.

Table of Contents

Install

To install the package, use meteor add:

meteor add react-meteor-data

You'll also need to install react if you have not already:

meteor npm install react

Changelog

check recent changes here

Usage

This package provides two ways to use Tracker reactive data in your React components:

  • a hook: useTracker (v2 only, requires React ^16.8)
  • a higher-order component (HOC): withTracker (v1 and v2).

The useTracker hook, introduced in version 2.0.0, embraces the benefits of hooks. Like all React hooks, it can only be used in function components, not in class components.

The withTracker HOC can be used with all components, function or class based.

It is not necessary to rewrite existing applications to use the useTracker hook instead of the existing withTracker HOC.

useTracker(reactiveFn) basic hook

You can use the useTracker hook to get the value of a Tracker reactive function in your React "function components." The reactive function will get re-run whenever its reactive inputs change, and the component will re-render with the new value.

useTracker manages its own state, and causes re-renders when necessary. There is no need to call React state setters from inside your reactiveFn. Instead, return the values from your reactiveFn and assign those to variables directly. When the reactiveFn updates, the variables will be updated, and the React component will re-render.

Arguments:

  • reactiveFn: A Tracker reactive function (receives the current computation).

The basic way to use useTracker is to simply pass it a reactive function, with no further fuss. This is the preferred configuration in many cases.

useTracker(reactiveFn, deps) hook with deps

You can pass an optional deps array as a second value. When provided, the computation will be retained, and reactive updates after the first run will run asynchronously from the react render execution frame. This array typically includes all variables from the outer scope "captured" in the closure passed as the 1st argument. For example, the value of a prop used in a subscription or a minimongo query; see example below.

This should be considered a low level optimization step for cases where your computations are somewhat long running - like a complex minimongo query. In many cases it's safe and even preferred to omit deps and allow the computation to run synchronously with render.

Arguments:

1import { useTracker } from 'meteor/react-meteor-data';
2
3// React function component.
4function Foo({ listId }) {
5  // This computation uses no value from the outer scope,
6  // and thus does not needs to pass a 'deps' argument.
7  // However, we can optimize the use of the computation
8  // by providing an empty deps array. With it, the
9  // computation will be retained instead of torn down and
10  // rebuilt on every render. useTracker will produce the
11  // same results either way.
12  const currentUser = useTracker(() => Meteor.user(), []);
13
14  // The following two computations both depend on the
15  // listId prop. When deps are specified, the computation
16  // will be retained.
17  const listLoading = useTracker(() => {
18    // Note that this subscription will get cleaned up
19    // when your component is unmounted or deps change.
20    const handle = Meteor.subscribe('todoList', listId);
21    return !handle.ready();
22  }, [listId]);
23  const tasks = useTracker(() => Tasks.find({ listId }).fetch(), [listId]);
24
25  return (
26    <h1>Hello {currentUser.username}</h1>
27    {listLoading ? (
28        <div>Loading</div>
29      ) : (
30        <div>
31          Here is the Todo list {listId}:
32          <ul>
33            {tasks.map(task => (
34              <li key={task._id}>{task.label}</li>
35            ))}
36          </ul>
37        </div>
38      )}
39  );
40}

Note: the eslint-plugin-react-hooks package provides ESLint hints to help detect missing values in the deps argument of React built-in hooks. It can be configured to also validate the deps argument of the useTracker hook or some other hooks, with the following eslintrc config:

1"react-hooks/exhaustive-deps": ["warn", { "additionalHooks": "useTracker|useSomeOtherHook|..." }]

useTracker(reactiveFn, deps, skipUpdate) or useTracker(reactiveFn, skipUpdate)

You may optionally pass a function as a second or third argument. The skipUpdate function can evaluate the return value of reactiveFn for changes, and control re-renders in sensitive cases. Note: This is not meant to be used with a deep compare (even fast-deep-equals), as in many cases that may actually lead to worse performance than allowing React to do it's thing. But as an example, you could use this to compare an updatedAt field between updates, or a subset of specific fields, if you aren't using the entire document in a subscription. As always with any optimization, measure first, then optimize second. Make sure you really need this before implementing it.

Arguments:

  • reactiveFn
  • deps? - optional - you may omit this, or pass a "falsy" value.
  • skipUpdate - A function which receives two arguments: (prev, next) => (prev === next). prev and next will match the type or data shape as that returned by reactiveFn. Note: A return value of true means the update will be "skipped". false means re-render will occur as normal. So the function should be looking for equivalence.
1import { useTracker } from 'meteor/react-meteor-data';
2
3// React function component.
4function Foo({ listId }) {
5  const tasks = useTracker(
6    () => Tasks.find({ listId }).fetch(), [listId],
7    (prev, next) => {
8      // prev and next will match the type returned by the reactiveFn
9      return prev.every((doc, i) => (
10        doc._id === next[i] && doc.updatedAt === next[i]
11      )) && prev.length === next.length;
12    }
13  );
14
15  return (
16    <h1>Hello {currentUser.username}</h1>
17    <div>
18      Here is the Todo list {listId}:
19      <ul>
20        {tasks.map(task => (
21          <li key={task._id}>{task.label}</li>
22        ))}
23      </ul>
24    </div>
25  );
26}

withTracker(reactiveFn) higher-order component

You can use the withTracker HOC to wrap your components and pass them additional props values from a Tracker reactive function. The reactive function will get re-run whenever its reactive inputs change, and the wrapped component will re-render with the new values for the additional props.

Arguments:

  • reactiveFn: a Tracker reactive function, getting the props as a parameter, and returning an object of additional props to pass to the wrapped component.
1import { withTracker } from 'meteor/react-meteor-data';
2
3// React component (function or class).
4function Foo({ listId, currentUser, listLoading, tasks }) {
5  return (
6    <h1>Hello {currentUser.username}</h1>
7    {listLoading ?
8      <div>Loading</div> :
9      <div>
10        Here is the Todo list {listId}:
11        <ul>{tasks.map(task => <li key={task._id}>{task.label}</li>)}</ul>
12      </div}
13  );
14}
15
16export default withTracker(({ listId }) => {
17  // Do all your reactive data access in this function.
18  // Note that this subscription will get cleaned up when your component is unmounted
19  const handle = Meteor.subscribe('todoList', listId);
20
21  return {
22    currentUser: Meteor.user(),
23    listLoading: !handle.ready(),
24    tasks: Tasks.find({ listId }).fetch(),
25  };
26})(Foo);

The returned component will, when rendered, render Foo (the "lower-order" component) with its provided props in addition to the result of the reactive function. So Foo will receive { listId } (provided by its parent) as well as { currentUser, listLoading, tasks } (added by the withTracker HOC).

For more information, see the React article in the Meteor Guide.

withTracker({ reactiveFn, pure, skipUpdate }) advanced container config

The withTracker HOC can receive a config object instead of a simple reactive function.

  • getMeteorData - The reactiveFn.
  • pure - true by default. Causes the resulting Container to be wrapped with React's memo().
  • skipUpdate - A function which receives two arguments: (prev, next) => (prev === next). prev and next will match the type or data shape as that returned by reactiveFn. Note: A return value of true means the update will be "skipped". false means re-render will occur as normal. So the function should be looking for equivalence.
1import { withTracker } from 'meteor/react-meteor-data';
2
3// React component (function or class).
4function Foo({ listId, currentUser, listLoading, tasks }) {
5  return (
6    <h1>Hello {currentUser.username}</h1>
7    {listLoading ?
8      <div>Loading</div> :
9      <div>
10        Here is the Todo list {listId}:
11        <ul>{tasks.map(task => <li key={task._id}>{task.label}</li>)}</ul>
12      </div}
13  );
14}
15
16export default withTracker({
17  getMeteorData ({ listId }) {
18    // Do all your reactive data access in this function.
19    // Note that this subscription will get cleaned up when your component is unmounted
20    const handle = Meteor.subscribe('todoList', listId);
21
22    return {
23      currentUser: Meteor.user(),
24      listLoading: !handle.ready(),
25      tasks: Tasks.find({ listId }).fetch(),
26    };
27  },
28  pure: true,
29  skipUpdate (prev, next) {
30    // prev and next will match the shape returned by the reactiveFn
31    return (
32      prev.currentUser?._id === next.currentUser?._id
33    ) && (
34      prev.listLoading === next.listLoading
35    ) && (
36      prev.tasks.every((doc, i) => (
37        doc._id === next[i] && doc.updatedAt === next[i]
38      ))
39      && prev.tasks.length === next.tasks.length
40    );
41  }
42})(Foo);

useSubscribe(subName, ...args) A convenient wrapper for subscriptions

useSubscribe is a convenient short hand for setting up a subscription. It is particularly useful when working with useFind, which should NOT be used for setting up subscriptions. At its core, it is a very simple wrapper around useTracker (with no deps) to create the subscription in a safe way, and allows you to avoid some of the ceremony around defining a factory and defining deps. Just pass the name of your subscription, and your arguments.

useSubscribe returns an isLoading function. You can call isLoading() to react to changes in the subscription's loading state. The isLoading function will both return the loading state of the subscription, and set up a reactivity for the loading state change. If you don't call this function, no re-render will occur when the loading state changes.

1// Note: isLoading is a function!
2const isLoading = useSubscribe('posts', groupId);
3const posts = useFind(() => Posts.find({ groupId }), [groupId]);
4
5if (isLoading()) {
6  return <Loading />
7} else {
8  return <ul>
9    {posts.map(post => <li key={post._id}>{post.title}</li>)}
10  </ul>
11}

If you want to conditionally subscribe, you can set the name field (the first argument) to a falsy value to bypass the subscription.

1const needsData = false;
2const isLoading = useSubscribe(needsData ? "my-pub" : null);
3
4// When a subscription is not used, isLoading() will always return false

useFind(cursorFactory, deps) Accelerate your lists

The useFind hook can substantially speed up the rendering (and rerendering) of lists coming from mongo queries (subscriptions). It does this by controlling document object references. By providing a highly tailored cursor management within the hook, using the Cursor.observe API, useFind carefully updates only the object references changed during a DDP update. This approach allows a tighter use of core React tools and philosophies to turbo charge your list renders. It is a very different approach from the more general purpose useTracker, and it requires a bit more set up. A notable difference is that you should NOT call .fetch(). useFind requires its factory to return a Mongo.Cursor object. You may also return null, if you want to conditionally set up the Cursor.

Here is an example in code:

1import React, { memo } from 'react'
2import { useFind } from 'meteor/react-meteor-data'
3import TestDocs from '/imports/api/collections/TestDocs'
4
5// Memoize the list item
6const ListItem = memo(({doc}) => {
7  return (
8    <li>{doc.id},{doc.updated}</li>
9  )
10})
11
12const Test = () => {
13  const docs = useFind(() => TestDocs.find(), [])
14  return (
15    <ul>
16      {docs.map(doc =>
17        <ListItem key={doc.id} doc={doc} />
18      )}
19    </ul>
20  )
21}
22
23// Later on, update a single document - notice only that single component is updated in the DOM
24TestDocs.update({ id: 2 }, { $inc: { someProp: 1 } })

If you want to conditionally call the find method based on some props configuration or anything else, return null from the factory.

1const docs = useFind(() => {
2  if (props.skip) {
3    return null
4  }
5  return TestDocs.find()
6}, [])

Concurrent Mode, Suspense and Error Boundaries

There are some additional considerations to keep in mind when using Concurrent Mode, Suspense and Error Boundaries, as each of these can cause React to cancel and discard (toss) a render, including the result of the first run of your reactive function. One of the things React developers often stress is that we should not create "side-effects" directly in the render method or in functional components. There are a number of good reasons for this, including allowing the React runtime to cancel renders. Limiting the use of side-effects allows features such as concurrent mode, suspense and error boundaries to work deterministically, without leaking memory or creating rogue processes. Care should be taken to avoid side effects in your reactive function for these reasons. (Note: this caution does not apply to Meteor specific side-effects like subscriptions, since those will be automatically cleaned up when useTracker's computation is disposed.)

Ideally, side-effects such as creating a Meteor computation would be done in useEffect. However, this is problematic for Meteor, which mixes an initial data query with setting up the computation to watch those data sources all in one initial run. If we wait to do that in useEffect, we'll end up rendering a minimum of 2 times (and using hacks for the first one) for every component which uses useTracker or withTracker, or not running at all in the initial render and still requiring a minimum of 2 renders, and complicating the API.

To work around this and keep things running fast, we are creating the computation in the render method directly, and doing a number of checks later in useEffect to make sure we keep that computation fresh and everything up to date, while also making sure to clean things up if we detect the render has been tossed. For the most part, this should all be transparent.

The important thing to understand is that your reactive function can be initially called more than once for a single render, because sometimes the work will be tossed. Additionally, useTracker will not call your reactive function reactively until the render is committed (until useEffect runs). If you have a particularly fast changing data source, this is worth understanding. With this very short possible suspension, there are checks in place to make sure the eventual result is always up to date with the current state of the reactive function. Once the render is "committed", and the component mounted, the computation is kept running, and everything will run as expected.

Suspendable version of hooks

suspense/useTracker

This is a version of useTracker that can be used with React Suspense.

For its first argument, a key is necessary, witch is used to identify the computation and to avoid recreating it when the component is re-rendered.

Its second argument is a function that can be async and reactive, this argument works similar to the original useTracker that does not suspend.

For its optional third argument, the dependency array, works similar to the useTracker that does not suspend, you pass in an array of variables that this tracking function depends upon.

For its optional fourth argument, the options object, works similar to the useTracker that does not suspend, you pass in a function for when should skip the update.

1import { useTracker } from 'meteor/react-meteor-data/suspense'
2import { useSubscribe } from 'meteor/react-meteor-data/suspense'
3
4function Tasks() { // this component will suspend
5  useSubscribe("tasks");
6  const { username } = useTracker("user", () => Meteor.user())  // Meteor.user() is async meteor 3.0
7  const tasksByUser = useTracker("tasksByUser", () =>
8          TasksCollection.find({username}, { sort: { createdAt: -1 } }).fetchAsync() // async call
9  );
10
11
12  // render the tasks
13}

Maintaining the reactive context

To maintain a reactive context using the new Meteor Async methods, we are using the new Tracker.withComputation API to maintain the reactive context of an async call, this is needed because otherwise it would be only called once, and the computation would never run again, this way, every time we have a new Link being added, this useTracker is ran.

1// needs Tracker.withComputation because otherwise it would be only called once, and the computation would never run again
2const docs = useTracker('name', async (c) => {
3    const placeholders = await fetch('https://jsonplaceholder.typicode.com/todos').then(x => x.json());
4    console.log(placeholders);
5    return active ? await Tracker.withComputation(c, () => LinksCollection.find().fetchAsync()) : null
6  }, [active]);
7

A rule of thumb is that if you are using a reactive function for example find + fetchAsync, it is nice to wrap it inside Tracker.withComputation to make sure that the computation is kept alive, if you are just calling that function that is not necessary, like the one bellow, will be always reactive.

1
2const docs = useTracker('name', () => LinksCollection.find().fetchAsync());
3

suspense/useSubscribe

This is a version of useSubscribe that can be used with React Suspense. It is similar to useSubscribe, it throws a promise and suspends the rendering until the promise is resolved. It does not return a Meteor Handle to control the subscription

1
2import { useTracker } from 'meteor/react-meteor-data/suspense'
3import { useSubscribe } from 'meteor/react-meteor-data/suspense'
4
5function Tasks() { // this component will suspend
6  useSubscribe("tasks");
7  const { username } = useTracker("user", () => Meteor.user())  // Meteor.user() is async meteor 3.0
8  const tasksByUser = useTracker("tasksByUser", () =>
9          TasksCollection.find({username}, { sort: { createdAt: -1 } }).fetchAsync() // async call
10  );
11
12
13// render the tasks
14}
15

suspense/useFind

This is a version of useFind that can be used with React Suspense. It has a few differences from the useFind without suspense, it throws a promise and suspends the rendering until the promise is resolved. It returns the result and it is reactive. You should pass as the first parameter the collection where is being searched upon and as the second parameter an array with the arguments, the same arguments that you would pass to the find method of the collection, third parameter is optional, and it is dependency array object. It's meant for the SSR, you don't have to use it if you're not interested in SSR.

1
2import { useFind } from 'meteor/react-meteor-data/suspense'
3import { useSubscribe } from 'meteor/react-meteor-data/suspense'
4
5function Tasks() { // this component will suspend
6  useSubscribe("tasks");
7  const tasksByUser = useFind(
8          TasksCollection,
9          [{}, { sort: { createdAt: -1 } }] 
10  );
11
12  // render the tasks
13}
14

Version compatibility notes

  • react-meteor-data v2.x :

    • useTracker hook + withTracker HOC
    • Requires React ^16.8.
    • Implementation is compatible with "React Suspense", concurrent mode and error boundaries.
    • The withTracker HOC is strictly backwards-compatible with the one provided in v1.x, the major version number is only motivated by the bump of React version requirement. Provided a compatible React version, existing Meteor apps leveraging the withTracker HOC can freely upgrade from v1.x to v2.x, and gain compatibility with future React versions.
    • The previously deprecated createContainer has been removed.
  • react-meteor-data v0.x :

    • withTracker HOC (+ createContainer, kept for backwards compatibility with early v0.x releases)
    • Requires React ^15.3 or ^16.0.
    • Implementation relies on React lifecycle methods (componentWillMount / componentWillUpdate) that are marked for deprecation in future React versions ("React Suspense").