Skip to content

If I use Atom on a mounted component, how can I avoid multiple reads when dependencies are updated? #2782

Answered by dmaskasky
hi-ogasawara asked this question in Q&A
Discussion options

You must be logged in to vote

In Jotai, set recomputes the dependents of an atom in place. This ensures that if those values are accessed in the very next line using get, they reflect the updated state. Consider the following example:

const a = atom(0);
const b = atom((get) => get(a) + 1);
const w = atom(null, (get, set) => {
  const b1 = get(b); // 1
  set(a, (v) => v + 1); // Recompute dependents of `a` here
  const b2 = get(b); // 2
});

This behavior means that every time an atom's value is updated with set, all its dependents are recalculated, even if they aren't accessed in the write function.

Edit: I am exploring changing this behavior so that only the dependents accessed with get will be recomputed in place, al…

Replies: 2 comments 12 replies

Comment options

You must be logged in to vote
1 reply
@hi-ogasawara
Comment options

Comment options

You must be logged in to vote
11 replies
@dai-shi
Comment options

@hi-ogasawara
Comment options

@dai-shi
Comment options

@dmaskasky
Comment options

Answer selected by dmaskasky
@dai-shi
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants