Skip to content

Commit

Permalink
docs: removes stop observing pattern section from performance page
Browse files Browse the repository at this point in the history
  • Loading branch information
mxthxngx committed Aug 22, 2024
1 parent c36f242 commit 8e27ccf
Showing 1 changed file with 0 additions and 59 deletions.
59 changes: 0 additions & 59 deletions docs/guides/performance.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -108,62 +108,3 @@ Ask yourself whether your atom is usually going to be frequently update or more
Let's imagine an atom containing an object that changes almost every second, it may not be best suited to "focus" on a specific properties of this object using `focusAtom`, because anyway they will all re-render in the same time, so best adding no overhead and not create any more atoms.

On the other hand, if your object has properties that rarely change, and most importantly, that change independently from the other properties, then you may want to use `focusAtom` or `selectAtom` to prevent un-necessary renders.

### "Stop observing" pattern

An example of pattern that can be interesting is to use `useMemo` to read an atom value only once, in order to prevent further renders even if the atom changes down the line.

Let's imagine a case, you have a list of toggles. Let's view 2 approaches for it:

### Standard pattern

We create our store of 3 toggles set to false

```tsx
const togglesAtom = atom([false, false, false])
```

Then, when the user clicks one toggle, we update it

```tsx
const Item = ({ index, val }) => {
const setToggles = useSetAtom(togglesAtom)
const onPress = () => {
setToggles(old => [...old, [index]: !val])
}
}

const List = () => {
const [toggles] = useAtom(togglesAtom)
return toggles.map((val, index) => <Item id={index} val={val} />)
}
```

With this approach, updating any toggle will cause all `<Item />` to re-render.

### Memoized pattern

Now let's try to memoize the value on the first render

```tsx
const List = () => {
const [toggles] = useMemo(() => useAtom(togglesAtom), [])
return toggles.map((val, index) => <Item id={index} initialValue={val} />)
}
```

But now it means we have to handle the changes locally in each `Item`

```tsx
const Item = ({ index, initialValue }) => {
const setToggles = useSetAtom(togglesAtom)
const [toggle, setToggle] = React.useMemo(() => useAtom(atom(val)), [])

const onPress = () => {
setToggle(!toggle) // Update locally
setToggles(old => [...old, [index]: !val]) // Update the main atom
}
}
```

Now if you update one toggle, it will only re-render the corresponding `<Item />`

0 comments on commit 8e27ccf

Please sign in to comment.