useSnapshot not updating when using useMemo #301
-
Yesterday, I ran into this very weird behavior where I was updating en element in an Array. After digging into it for hours, I discovered it was caused by a This doesn't make any sense to me and I feel that it's just a very stupid thing that I overlooked, and I would appreciate it very much if someone could take a look and see what's going on there. The only difference is that I'm on an M1 MacBook, but I don't see how that can affect the behavior Here is a link to the CodeSandbox: Thank you very much 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Here are also two screen recordings of the same behavior. CodeSandbox: Local: |
Beta Was this translation helpful? Give feedback.
-
Yeah, proxy based tracking does not work well with
In your case, Technically, we have an API for a solution https://github.com/dai-shi/proxy-compare/blob/main/src/index.ts#L276, but it's too hard to explain. It is fine to use memo/useMemo for primitive values. So, the best is to destructure before using memo. Your use case can't do it, though. |
Beta Was this translation helpful? Give feedback.
Yeah, proxy based tracking does not work well with
React.memo
.https://github.com/pmndrs/valtio/wiki/Some-gotchas#using-reactmemo-with-object-props-may-result-in-unexpected-behavior
useMemo
is the same too.In your case,
slices
is an array which is wrapped with a proxy, so having that in useMemo prevents from correctly tracking the usage. This is very unfortunate. I ended up to educate about avoiding useMemo/memo with valtio.Technically, we have an API for a solution https://github.com/dai-shi/proxy-compare/blob/main/src/index.ts#L276, but it's too hard to explain.
It is fine to use memo/useMemo for primitive values. So, the best is to destructure before using memo. Your use case can't d…