Skip to content

Commit

Permalink
fix(docs): async guide
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Dec 9, 2024
1 parent e21edb3 commit edf7f23
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions docs/guides/async.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,32 @@ subscribe(store, () => {
})
```

## Suspend your React components
#### Suspend your components

Valtio supports React Suspense and will throw promises that you access within a components render function. This eliminates all the async back-and-forth. You can access your data directly while the parent is responsible for fallback state and error handling.
Valtio is compatible with React 19 `use` hook. This eliminates all the async back-and-forth, you can access your data directly while the parent is responsible for fallback state and error handling.

```jsx
import { use } from 'react' // React 19
// import { use } from 'react18-use' // React 18

const state = proxy({ post: fetch(url).then((res) => res.json()) })

function Post() {
const snap = useSnapshot(state)
return <div>{snap.post.title}</div>
return <div>{use(snap.post).title}</div>
}

function App() {
return (
<Suspense fallback="Loading...">
<Suspense fallback={<span>waiting...</span>}>
<Post />
</Suspense>
)
}
```

It still suffers from "de-opt", which prevents `useTransition` to work well. To mitigate it, there is a third-party library [use-valtio](https://github.com/valtiojs/use-valtio).

## Codesandbox Pokemon fetch demo

https://codesandbox.io/s/valtio-pokemon-fetch-x1lkbj?file=/src/App.tsx
Expand Down

0 comments on commit edf7f23

Please sign in to comment.