-
-
Notifications
You must be signed in to change notification settings - Fork 70
Description
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.
- state = { a: { b: 1, c: 2 } }
- usage = ['.a.b', '.a.c']
- state = { a: { b: 1, c: 3 } }
- usage = ['.a.c'] // not ['.a', '.a.c'], because we only care leaves.
- state = { a: { b: 4, c: 3 } }
- 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
.