Kevin Powell - CommunityKP-C
Kevin Powell - Community•3y ago•
2 replies
Nikita

useOptimistic - example needed - codesandbox / stackblitz / github

I need to change data immediately without waiting for response from server - https://www.youtube.com/watch?v=wg3xQogkZDA&ab_channel=SonnySangha

If you did this with useOptimistic or react-query - please send me like to example

Also I tried to do it and got this error
TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_1__.experimental_useOptimistic) is not a function or its return value is not iterable

To reproduce:
1. pnpm create-next-app@latest
2. paste this in page.tsx
"use client"

import { experimental_useOptimistic as useOptimistic } from "react"

export default function Home() {
  let testNumber = 99
  const [optimisticTest, optimisticTestFunction] = useOptimistic(
    testNumber,
    (state, amount: number) => state + Number(amount),
  )
  async function updateNumber(amount: number) {
    optimisticTestFunction(amount)
  }
  return (
    <div>
      {optimisticTest}
      <button onClick={() => updateNumber(-1)}>optimistic test</button>
      <button onClick={() => updateNumber(+1)}>optimistic test</button>
    </div>
  )
}
YouTubeSonny Sangha
🚨 Join my course Zero to Full Stack Hero: https://www.papareact.com/course

The useOptimistic hook provides a way to implement OPTIMISTIC updates. These Optimistic updates enhance the user experience by making the app appear more responsive to the user by displaying instant results on the front end.

šŸ”“ LOOKING FOR THE CODE FROM THE BUILDS? šŸ› ļø
ht...
Learn the useOptimistic Hook in 19 minutes (Next.js 13 For Beginners)
Was this page helpful?