State
/ API Reference
State
/ API Reference

useOptimisticState

A hook for managing state with optimistic updates.
It uses useOptimistic (new tab) under the hood, but provides a useState (new tab)-like API.
It automatically starts a transition when the state is updated and calls the provided update function.

The Gist

import { useOptimisticState } from '@weser/state'

type Props = {
  count: number
  updateCount: (count: number) => Promise<void>
}
function Counter({ count, updateCount }: Props) {
  const [state, setState] = useOptimisticState(count, updateCount)

  return (
    <div>
      <p>{state}</p>
      <button onClick={() => setState(state + 1)}>Increment</button>
      <button onClick={() => setState(state - 1)}>Decrement</button>
    </div>
  )
}
import { getCount, updateCount } from './api'

async function App() {
  const count = await getCount()

  return <Counter count={count} updateCount={updateCount} />
}

Parameters

ParameterTypeDescription
initialStateTThe initial value of the state.
updater(state: T) => Promise<void>The actual update procedure, usually a server action mutating your database.

Returns

([T, Dispatch<SetStateAction<T>>]) A tuple where the first element is the state and the second element is a function to update the state. The same signature as React's useState (new tab).

On this page