State
/ API ReferenceState
/ API ReferenceuseOptimisticState
A hook for managing state with optimistic updates.
It uses useOptimistic under the hood, but provides a useState-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
| Parameter | Type | Description |
|---|---|---|
| initialState | T | The 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.
© 2024-present Robin Weser. All Rights Reserved.