Closed kevinschaich closed 2 days ago
cc: @dai-shi would love your thoughts and advice
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 })
You can use withHistory from jotai-history to assist with prev/curr values.
I think it would be great if it could be something like withCompare
and accepted both derived and primitive atoms. Then we could deprecate atomWithCompare
.
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.
https://github.com/pmndrs/jotai/issues/1158, https://github.com/pmndrs/jotai/issues/783, https://github.com/pmndrs/jotai/issues/324, https://github.com/pmndrs/jotai/issues/1175, https://github.com/pmndrs/jotai/issues/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