Using React's useOptimistic Hook

November, 26th 2024 2 min read

Optimistic updates improve user experience by reflecting changes in the UI instantly, even before server confirmation. React’s useOptimistic hook, introduced in React 18, simplifies managing these temporary state updates. This article demonstrates how to leverage useOptimistic to enhance responsiveness and error handling in your applications.

What is useOptimistic?

The useOptimistic hook helps manage temporary states during optimistic updates, providing a declarative way to handle changes while waiting for server responses.

When to Use useOptimistic?

The hook is ideal for:

  1. Updating shopping cart items in e-commerce apps.
  2. Handling votes or likes in social platforms.
  3. Managing temporary edits in collaborative tools.

Syntax of useOptimistic

js
const [state, updateState] = useOptimistic(initialState, reducerFunction);
  • initialState: The starting state for your updates.
  • reducerFunction: A function defining how actions change the state.

Example: Optimistic Updates for a Voting System

js
import { useOptimistic } from 'react';

function VotingApp({ postId, initialVotes }) {
  const [votes, updateVotes] = useOptimistic(initialVotes, (state, action) => {
    switch (action.type) {
      case 'increment':
        return state + 1;
      case 'decrement':
        return state - 1;
      default:
        return state;
    }
  });

  const handleVote = async type => {
    updateVotes({ type });
    try {
      await fetch(`/api/vote`, {
        method: 'POST',
        body: JSON.stringify({ postId, type }),
      });
    } catch {
      alert('Failed to register your vote. Please try again.');
      updateVotes({ type: type === 'increment' ? 'decrement' : 'increment' });
    }
  };

  return (
    <div>
      <h3>Votes: {votes}</h3>
      <button onClick={() => handleVote('increment')}>Upvote</button>
      <button onClick={() => handleVote('decrement')}>Downvote</button>
    </div>
  );
}

How useOptimistic Works

  1. Immediate Feedback: Updates the UI instantly.
  2. Error Handling: Reverts the state if server fails.
  3. Centralized Logic: Reducer keeps behavior predictable.

Benefits

  • Improved UX
  • Less boilerplate
  • Flexible for many UI interactions

Conclusion

React’s useOptimistic hook streamlines optimistic UI patterns, helping you build smooth, responsive interfaces with minimal complexity.