Function

import { createCache } from '@glimmer/tracking/primitives/cache';

Receives a function, and returns a wrapped version of it that memoizes based on autotracking. The function will only rerun whenever any tracked values used within it have changed. Otherwise, it will return the previous value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { tracked } from '@glimmer/tracking';
import { createCache, getValue } from '@glimmer/tracking/primitives/cache';

class State {
  @tracked value;
}

let state = new State();
let computeCount = 0;

let counter = createCache(() => {
  // consume the state. Now, `counter` will
  // only rerun if `state.value` changes.
  state.value;

  return ++computeCount;
});

getValue(counter); // 1

// returns the same value because no tracked state has changed
getValue(counter); // 1

state.value = 'foo';

// reruns because a tracked value used in the function has changed,
// incermenting the counter
getValue(counter); // 2