Util RFC: derivedAtomWithCompare
#2796
Replies: 3 comments 4 replies
-
cc: @dai-shi would love your thoughts and advice |
Beta Was this translation helpful? Give feedback.
-
Nice RFC. I agree that compare functionality could be brought to derived atoms to make ergonomics better. I would love to see this added as a utility to jotai-history. Feel free to submit a PR. A few thoughts below:
const prevAtom = atom(() => { previousValue })
|
Beta Was this translation helpful? Give feedback.
-
Something I'm unclear on after some additional experimentation yesterday –– is achieving the desired goal possible with the vanilla atom model? Implementation details aside, re: the commented line above ( |
Beta Was this translation helpful? Give feedback.
-
Use case:
You have a lot of derived atoms that are selecting from large object atoms, and want to avoid the small ones publishing changes if their derived values don't change. Publishing changes every time can be undesirable for several reasons:
With vanilla jotai and no utils, you might have something like this
This is probably the right behavior for most people, but it's not the right behavior for everyone.
Existing discussions (non-exhaustive):
Many people have asked about this. If we have a snippet somewhere I'm happy to use that instead of the proposed code below.
#1158, #783, #324, #1175, #26
Proposal:
derivedAtomWithCompare
: derived atom that keeps track of the previous value and deeply compares it to the next value, do not republish changes to subscribers if they are the sameread
function which accepts aGetter
Differences from existing utils:
selectAtom
, but the goal here is to provide a generic read-only atom that can do anything a normal derived atom can (needs access to aGetter
)atomWithCache
, but you want to check if the returned value is deeply equal to the previous returned value, rather than the dependencies of theget
function. The dependency atoms will most likely change every time because they keep a lot of other things unrelated to this atom value.atomWithCompare
, but your read function needs to be dynamic and read from other atoms, rather than having the returned atom be aPrimitiveAtom
that gets set directly.bunshi
(formerlyjotai-molecules
)? I'm not entirely sure.Current Progress:
It's not working 100% but I think I'm pretty close.
Assignee:
@kevinschaich
Beta Was this translation helpful? Give feedback.
All reactions