Implements "Fast Sync" using the useOptimistic hook. Use when you want to provide instant feedback for user actions like booking or liking while the backend processes.
useOptimistic hook in a Client Component.useOptimistic.'use client'
import { useOptimistic } from 'react';
import { bookTourAction } from '@/actions/bookings';
export function BookingButton({ tourId, initialStatus }: { tourId: string, initialStatus: string }) {
const [optimisticStatus, setOptimisticStatus] = useOptimistic(
initialStatus,
(_, newStatus: string) => newStatus
);
const handleAction = async () => {
setOptimisticStatus('confirmed'); // Optimistic state
const result = await bookTourAction(tourId);
if (!result.success) {
// Reversion happens automatically on re-render if we don't manually handle it
}
};
return (
<button onClick={handleAction}>
{optimisticStatus === 'confirmed' ? 'Booked!' : 'Book Now'}
</button>
);
}
revalidatePath in the server action to ensure the official state replaces the optimistic one.