From f04a458d91fa762cf8e685f4dbc1231e16fde821 Mon Sep 17 00:00:00 2001 From: David Maskasky Date: Fri, 13 Oct 2023 12:44:56 -0700 Subject: [PATCH] doc: Fix CodeSandbox example and add 'Comparison with useEffect' section to jotai-effect doc --- docs/integrations/effect.mdx | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/integrations/effect.mdx b/docs/integrations/effect.mdx index 11b19b05e1..3856b0d22a 100644 --- a/docs/integrations/effect.mdx +++ b/docs/integrations/effect.mdx @@ -77,7 +77,7 @@ function MyComponent() { } ``` - + ## The `atomEffect` behavior @@ -294,3 +294,22 @@ Aside from mount events, the effect runs when any of its dependencies change val ``` + +### 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 you “hook into” React 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. + + + +We can fix our example while maintaining the loose coupling of `` by replacing useEffect with `atomEffect`. + + + +`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.