Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(scope): Add tips gathered from common issues #29

Merged
merged 1 commit into from
Apr 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,28 @@
👻🔭

https://jotai.org/docs/integrations/scope

## Pro Tips

1. Within a `ScopeProvider`, although an atom may not be scoped, its `atom.read` function could be called multiple times. **Therefore, do not use `atom.read` to perform side effects.**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could be called multiple times

Why is this?


NOTE: Async atoms always have side effects. To handle it, add additional code to prevent extra side effects. You can check this [issue](https://github.com/jotaijs/jotai-scope/issues/25#issuecomment-2014498893) as an example.

2. Scoping a derived atom has no behavioral effect. Avoid it.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid it.

If this pattern is to be prohibited, then why not solve this with typescript?


Derived atoms are merely proxies of primitive atoms. When scoping a derived atom, although the atom itself is copied, all of those copies still reference the same primitive atom, so their values are still shared.

It is a common pattern in Jotai to wrap the primitive atom within a utility function. To scope it properly, you should expose the primitive atom and then apply the scoping to it.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should encourage exposing base atoms. They are an implementation detail of the custom atom. Most developers use custom atoms from libraries out of the box. How would I scope atoms like atomWithMachine?


``` javascript
function someAtomUtility(initialValue) {
// This is the primitive atom. Return it and then scope it.
const anAtom = atom(initialValue)

// Be careful, this is a derived atom! Scoping it has no effect.
return atom(
(get) => get(anAtom),
(get, set, update) => set(anAtom, update)
),
}
```
Loading