MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
GraphQL Mutations and Optimistic UI Updates0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
13.1GraphQL Fundamentals and Apollo Client Setup13.2Executing GraphQL Queries with useQuery13.3GraphQL Mutations and Optimistic UI Updates13.4Real-Time GraphQL Subscriptions with WebSockets
HomeTutorialsReact.js for AdvancedGraphQL Mutations and Optimistic UI Updates
Real-Time GraphQL Subscriptions with WebSockets

GraphQL Mutations and Optimistic UI Updates

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While queries read data, Mutations modify server-side resources. In high-performance enterprise applications, waiting 500ms for a network roundtrip before updating a "Like", "Checkmark", or "Status" button creates perceived lag. Optimistic UI updates immediately render expected mutations in the UI before server confirmation, rolling back cleanly if the request fails.


1. Anatomy of useMutation

1const [mutateFunction, { data, loading, error }] = useMutation(MUTATION_DOCUMENT, options);
  • mutateFunction(options): Dispatches the mutation request.
  • refetchQueries: Specifies queries to refetch after mutation succeeds.
  • update(cache, { data }): Directly updates the normalized cache without triggering extra network requests.
  • optimisticResponse: Provides temporary synthetic data written to the cache immediately upon dispatch.

2. Implementing Optimistic Updates

Consider toggling a task's completed status:

1import React from "react";
2import { gql, useMutation } from "@apollo/client";
3 
4const TOGGLE_TASK_MUTATION = gql`
5 mutation ToggleTask($id: ID!, $completed: Boolean!) {
6 toggleTask(id: $id, completed: $completed) {
7 id
8 completed
9 __typename
10 }
11 }
12`;
13 
14interface TaskItemProps {
15 task: {
16 id: string;
17 title: string;
18 completed: boolean;
19 };
20}
21 
22export function TaskItem({ task }: TaskItemProps) {
23 const [toggleTask, { loading }] = useMutation(TOGGLE_TASK_MUTATION);
24 
25 const handleToggle = () => {
26 toggleTask({
27 variables: {
28 id: task.id,
29 completed: !task.completed,
30 },
31 // 1. OPTIMISTIC RESPONSE: Rendered instantly in 0ms!
32 optimisticResponse: {
33 toggleTask: {
34 id: task.id,
35 completed: !task.completed,
36 __typename: "Task",
37 },
38 },
39 // 2. Direct cache manipulation (if not automatically normalized by ID)
40 update(cache, { data }) {
41 if (!data?.toggleTask) return;
42 cache.modify({
43 id: cache.identify({ __typename: "Task", id: task.id }),
44 fields: {
45 completed() {
46 return data.toggleTask.completed;
47 },
48 },
49 });
50 },
51 });
52 };
53 
54 return (
55 <div className="flex items-center justify-between p-3 bg-slate-900 border border-slate-800 rounded-lg text-white">
56 <span className={task.completed ? "line-through text-slate-500" : "text-slate-200"}>
57 {task.title}
58 </span>
59 
60 <button
61 onClick={handleToggle}
62 className={`px-3 py-1 rounded text-xs font-semibold transition ${
63 task.completed
64 ? "bg-slate-800 text-slate-400 hover:bg-slate-700"
65 : "bg-cyan-600 text-white hover:bg-cyan-500"
66 }`}
67 >
68 {task.completed ? "Mark Incomplete" : "Mark Done"}
69 </button>
70 </div>
71 );
72}

3. How Apollo Handles Failures

If the server rejects the mutation (e.g. 500 Internal Server Error or permission denied):

  1. 1
    Apollo Client detects the network error.
  2. 2
    It automatically rolls back the optimistic snapshot from the cache.
  3. 3
    The UI instantaneously returns to its previous valid state without manual recovery code!

4. Cache Eviction on Deletion

When deleting records, use cache.evict to purge the deleted entity from memory:

1const [deleteTask] = useMutation(DELETE_TASK_MUTATION, {
2 update(cache, { data }) {
3 const normalizedId = cache.identify({ __typename: "Task", id: deletedId });
4 cache.evict({ id: normalizedId });
5 cache.gc(); // Garbage collect dangling references
6 },
7});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary benefit of an "Optimistic UI Update"?
Question 2
What happens if an optimistic mutation fails due to a network outage or 500 error?
Question 3
Why is __typename mandatory inside optimisticResponse payloads?
Question 4
When should you use cache.evict({ id }) inside a mutation's update callback?
Question 5
What is the trade-off between refetchQueries and manual cache.modify()?
Next Lesson

Real-Time GraphQL Subscriptions with WebSockets

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Executing GraphQL Queries with useQueryReal-Time GraphQL Subscriptions with WebSockets

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext