Functions
React useOptimistic
React useOptimistic presents a temporary state during an Action. A pure reducer can reapply pending changes to updated confirmed state. Handle failures and reconcile with the authoritative result. The example uses simulated client-only delay, not actual persistence. Source: https://react.dev/reference/react/useOptimistic. Documentation-reviewed illustrative draft; installed declarations and runtime not verified.
Formal Syntax & Structure
nextjs syntaxnextjs
useOptimistic(value, reducer?)Working Example
Example Snippetnextjs
'use client';import { useOptimistic, useState } from 'react';export default function Preview() { const [confirmed, setConfirmed] = useState('Fern'); const [error, setError] = useState(''); const [title, setTitle] = useOptimistic(confirmed); async function change(data: FormData) { const next = String(data.get('title') ?? '').trim(); setError(''); setTitle(next); await new Promise(resolve => setTimeout(resolve, 300)); if (next.length < 3) { setError('Title rejected'); return; } setConfirmed(next); } return <form action={change}> <label htmlFor="rename">New title</label><input id="rename" name="title" /> <button>Preview change</button><p>Title: {title}</p> <p role="status">{error}</p> </form>;}