Skip to content

Commit

Permalink
doc: Fix CodeSandbox example and add 'Comparison with useEffect' sect…
Browse files Browse the repository at this point in the history
…ion to jotai-effect doc
  • Loading branch information
David Maskasky committed Oct 13, 2023
1 parent e7f0255 commit f04a458
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion docs/integrations/effect.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ function MyComponent() {
}
```

<Codesandbox id="85zrzn" />
<CodeSandbox id="tg9xsf" />

## The `atomEffect` behavior

Expand Down Expand Up @@ -294,3 +294,22 @@ Aside from mount events, the effect runs when any of its dependencies change val
```

</details>

### Comparison with useEffect

[useEffect](https://react.dev/reference/react/useEffect) is a React Hook that lets you synchronize a component
with an external system.

Hooks are functions that let youhook intoReact state and lifecycle features from function components. They are a way to reuse, but not centralize, stateful logic. When we want to share logic between two JavaScript functions, we extract it to a third function, a custom hook.

Each call to a hook has a completely isolated state. This isolation is can be referred to as _component-scoped_. Mixing a global state management library such as Jotai with useEffect can have some unexpected results.

Consider the setup below. useMessages is called in two components. Since the useEffect inside is component-scoped calls, this results in two document event listeners being set up.

<CodeSandbox id="855hd4" />

We can fix our example while maintaining the loose coupling of `<MessageInput>` by replacing useEffect with `atomEffect`.

<CodeSandbox id="gzq9jg" />

`atomEffect` is scoped to the store context rather than the component. This guarantees that a single effect will be used regardless of how many times it is called. When implementing behavior with a global state management solution, be mindful of mixing component-scope and global-scope.

0 comments on commit f04a458

Please sign in to comment.