← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 10 of 10

Optimistic UI Updates करना

एक optimistic update ऐसा है जैसे आप अपने friend को पहले बोल दें 'हां, मैं आ जाऊंगा!' बिना अपना calendar check किए — आप मान लेते हैं कि हां होगा और अगर कोई conflict निकले तभी खुद को correct करते हैं।
Syntax
markup
function handleAction() {
  const previous = state;
  setState(optimisticValue); // update the UI immediately
  sendToServer().catch(() => setState(previous)); // revert on failure
}

Server Confirm करने से पहले UI Update करना

Normal flow में, आप UI update करने से पहले एक server response का wait करेंगे, जो छोटे, usually-successful actions के लिए sluggish feel हो सकता है। एक optimistic update इसे flip कर देता है: local state को तुरंत बदल दें, success मानते हुए, फिर background में असली request quietly fire करें।

Note: Optimistic updates उन actions के लिए सबसे अच्छे काम करते हैं जो rarely fail होते हैं, जैसे एक post like करना या एक checkbox toggle करना — visible revert का risk कम है।
Warning: ऐसे actions के लिए जिनमें failure का meaningful chance हो (जैसे एक payment), failure पर sudden visual revert पहले से confirmation का wait करने से ज़्यादा jarring हो सकता है।

उदाहरण: Updating the UI Before the Server Confirms

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [liked, setLiked] = React.useState(false);
  const handleLike = () => {
    setLiked(true); // update immediately
    // fetch('/api/like', { method: 'POST' }); // fires in background
  };
  return <button onClick={handleLike}>{liked ? "Liked!" : "Like"}</button>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Failure पर Revert करना

चूंकि optimistic update success मान लेता है, आपको एक plan चाहिए उस situation के लिए जब असली request fail हो जाए: बदलने से पहले previous value store करना आपको UI को exact prior state में वापस roll back करने देता है अगर server एक error से respond करे।

Note: Previous value को optimistic change apply करने से ठीक पहले एक local variable में capture करें, ताकि यह catch block में available हो।
Warning: Revert step skip करने का मतलब है एक failed request UI को true server state के बारे में silently लेट बोलने देती है।

उदाहरण: Reverting on Failure

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [liked, setLiked] = React.useState(false);
  const handleLike = () => {
    const previous = liked;
    setLiked(true);
    const requestFailed = true; // simulate a failed request
    if (requestFailed) setLiked(previous);
  };
  return <button onClick={handleLike}>{liked ? "Liked!" : "Like (will revert)"}</button>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Lists के लिए Optimistic Updates

यही idea lists से items add या remove करने पर भी extend होता है: नया item local state में तुरंत add करें, background में असली request भेजें, और अगर request आखिरकार fail हो जाए तो उसे फिर हटा दें (या एक error दिखाएं)।

Note: Optimistically-added items को एक temporary local ID दें, request succeed होने पर इसे असली server-assigned ID से replace करते हुए।
Warning: Revert के दौरान गलत item हटाना (अगर IDs carefully track न हों) silently list से एक अलग, unrelated item delete कर सकता है।

उदाहरण: Optimistic Updates for Lists

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [items, setItems] = React.useState(["First item"]);
  const addItem = () => {
    setItems(prev => [...prev, "New item (optimistic)"]);
    // fetch('/api/items', { method: 'POST' }).catch(() => {
    //   setItems(prev => prev.slice(0, -1)); // revert on failure
    // });
  };
  return <div><button onClick={addItem}>Add Item</button><ul>{items.map((i, idx) => <li key={idx}>{i}</li>)}</ul></div>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. अगर असली server request fail हो जाए तो optimistic change revert न करना, जिससे UI permanently incorrect data दिखाता रहता है।
  2. Optimistic update को request के बाद apply करना instead of पहले, जो instant feel होने का पूरा point defeat करता है।
  3. कोई visual cue न देना कि एक update pending confirmation है, अगर वह use case के लिए मायने रखता हो।
चैप्टर सारांश
  • एक optimistic update UI को तुरंत बदल देता है, success मानते हुए, server के response का wait करने से पहले।
  • यह post like करने या एक to-do check off करने जैसे actions को sluggish के बजाय instant feel करवाता है।
  • अगर असली request fail हो, तो UI को अपनी previous state में rolled back होना चाहिए।
  • Update करने से पहले previous value store करना revert करना आसान बना देता है जब ज़रूरत हो।
ब्राउज़र सपोर्ट

कोई React-version restriction नहीं — useState और standard request handling से बनाया गया एक UI pattern।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.