Skip to content

What is trackMemo and when to use it #30

@dai-shi

Description

@dai-shi

What is state usage tracking

Let's say we have a state like this.

const state = { a: { b: 1, c: 2 } };

We then use this state in render:

return (
  <div>{state.a.b}</div>
);

With state usage tracking, it will mark .a.b is used.
So, only when state.a.b is changed, it triggers re-render.
If only state.a.c is change, it won't.

What would be a problem

If the render function is really pure, that is, it is consistent with using state in every render,
there's no problem.
However, suppose the function uses state.a.b for the first time,
but does not use it next time, then it will forget the usage marked in the first time.
If that's intentional, it fine. But, this could happen with memoization unexpectedly.

For example:

const b = useMemo(state => state.a.b, [state.a]);
const x = state.a.c + 1;

This might cause a problem.

  1. state = { a: { b: 1, c: 2 } }
  2. usage = ['.a.b', '.a.c']
  3. state = { a: { b: 1, c: 3 } }
  4. usage = ['.a.c'] // not ['.a', '.a.c'], because we only care leaves.
  5. state = { a: { b: 4, c: 3 } }
  6. no re-render

When we should use trackMemo

If a render function uses some kind of memoization based on object identity.
We should mark the whole object as used. This is what trackMemo is for.

Its implementation seems trivial, but this is only required if render is not pure for using state.
Only such case known so far is memoization. So, it's named trackMemo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions