Blog>
Snippets

Optimistic UI Updates for Instant Feedback

Demonstrate integrating optimistic UI updates in the context of asynchronous validation, where the UI assumes success and updates accordingly until the server response is received.
const [usernameAvailable, setUsernameAvailable] = useState(true);
Initial state assuming the username is available, representing optimistic UI updates.
const validateUsername = async (username) => {
  // Optimistically assume username is available
  setUsernameAvailable(true);
  try {
    const response = await fetch(`/api/validate-username?username=${username}`);
    const { isAvailable } = await response.json();
    setUsernameAvailable(isAvailable);
  } catch (error) {
    console.error('Error validating username', error);
    setUsernameAvailable(false); // Assume not available on error
  }
};
Function performing the asynchronous validation. Initially, it optimistically updates the UI to reflect the username is available. It then performs the server request, and upon receiving a response, updates the state based on actual availability.
useEffect(() => {
  if (username) {
    validateUsername(username);
  }
}, [username]);
Effect hook that calls validateUsername function whenever the username changes. This allows for real-time feedback as the user types.