tomo1127
tomo1127

Reputation: 67

useTracker dependency array? react meteor

I have a question about useTracker from meteor and react.

  const sample = useTracker(
    () => func1(),
    [slug],
  );

Does this mean every time sulg gets changed, fun1 gets running and sample will get a new value? like a dependency array with useEffect?

Thank you

Upvotes: 0

Views: 925

Answers (1)

Jankapunkt
Jankapunkt

Reputation: 8413

You are partially right, if slug updates your function re-runs but it would also re-run if the function func1 is using a reactive data source.

The documentation for useTracker has a pretty good example:

  // This computation uses no value from the outer scope,
  // and thus does not needs to pass a 'deps' argument.
  // However, we can optimize the use of the computation
  // by providing an empty deps array. With it, the
  // computation will be retained instead of torn down and
  // rebuilt on every render. useTracker will produce the
  // same results either way.
  const currentUser = useTracker(() => Meteor.user(), []);

  // The following two computations both depend on the
  // listId prop. When deps are specified, the computation
  // will be retained.
  const listLoading = useTracker(() => {
    // Note that this subscription will get cleaned up
    // when your component is unmounted or deps change.
    const handle = Meteor.subscribe('todoList', listId);
    return !handle.ready();
  }, [listId]);

  // my personal note: this function updates either if
  // lsitId changes OR if Tasks get updated by pub/sub
  // for example because documents have been inserted/updated/removed
  // on the server
  const tasks = useTracker(() => Tasks.find({ listId }).fetch(), [listId]);

see: https://github.com/meteor/react-packages/tree/master/packages/react-meteor-data#usetrackerreactivefn-deps-hook-with-deps

Upvotes: 1

Related Questions