After multiple attempts, I discovered that I also need to place the logic that actually updates the state inside the startTransition callback for the code to execute as expected. Below is my code:
const toggleIsFavorited = async () => {
setError('');
const nextIsFavorited = !isFavorited;
// Wrap optimistic update in startTransition
startTransition(async () => {
setOptimisticIsFavorited(nextIsFavorited);
try {
const result = await toggleFavorite();
if (result === 'success') {
setIsFavorited(nextIsFavorited);
} else {
setError('Failed to add to favorites!');
}
} catch (err) {
setError('An error occurred');
}
});
};
I still don't know why :(