diff --git a/src/content/reference/react/useOptimistic.md b/src/content/reference/react/useOptimistic.md index 2095a4198f7..179b4c43df3 100644 --- a/src/content/reference/react/useOptimistic.md +++ b/src/content/reference/react/useOptimistic.md @@ -59,6 +59,11 @@ function AppContainer() { * `optimisticState`: The resulting optimistic state. It is equal to `state` unless an action is pending, in which case it is equal to the value returned by `updateFn`. * `addOptimistic`: `addOptimistic` is the dispatching function to call when you have an optimistic update. It takes one argument, `optimisticValue`, of any type and will call the `updateFn` with `state` and `optimisticValue`. + +#### Caveats {/*caveats*/} + +* An optimistic state update needs to be called in an action or wrapped with `startTransition`. If it's used outside an action or a transition React will throw an error. + --- ## Usage {/*usage*/} @@ -143,3 +148,67 @@ export async function deliverMessage(message) { ``` + +--- + +### Optimistically update the UI while waiting for a network request {/*optimistically-update-while-waiting-for-network*/} + + + +```js like-button.js active +import { startTransition, useOptimistic } from "react"; + +export function LikeButton({ likes, updateLikes, disabled }) { + const [optimisticLikes, addOptimisticLike] = useOptimistic( + likes, + (likes) => likes + 1 + ); + + async function addLike() { + startTransition(() => { + addOptimisticLike(); + updateLikes(likes); + }) + } + + return ( + + ); +} +``` + + +```js App.js +import { useState } from "react"; +import { LikeButton } from "./like-button.js"; + +export default function App() { + const [likes, setLikes] = useState(0); + const [updating, setUpdating] = useState(false); + async function updateLikes(num) { + setUpdating(true); + await new Promise((res) => setTimeout(res, 1000)); + setLikes(num + 1); + setUpdating(false); + } + return ( + + ); +} +``` + +```json package.json hidden +{ + "dependencies": { + "react": "experimental", + "react-dom": "experimental", + "react-scripts": "^5.0.0" + }, + "main": "/index.js", + "devDependencies": {} +} +``` + + \ No newline at end of file