Bird
Raised Fist0
GraphQLquery~15 mins

Refetching and polling in GraphQL - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Refetching and polling
What is it?
Refetching and polling are ways to keep data fresh in applications using GraphQL. Refetching means asking the server again for data when you want to update it. Polling means automatically asking the server for new data at regular time intervals. Both help apps show the latest information without needing a full page reload.
Why it matters
Without refetching or polling, apps might show old or outdated data, confusing users or causing mistakes. For example, a chat app without polling might not show new messages unless you refresh manually. These techniques keep apps responsive and reliable by ensuring data stays current.
Where it fits
Before learning refetching and polling, you should understand basic GraphQL queries and how to fetch data. After this, you can learn about subscriptions for real-time updates and caching strategies to optimize performance.
Mental Model
Core Idea
Refetching and polling are methods to repeatedly ask the server for updated data to keep the app's information current.
Think of it like...
It's like checking your mailbox: refetching is going to the mailbox when you remember to check, while polling is setting an alarm to check the mailbox every hour automatically.
┌───────────────┐       ┌───────────────┐
│   Client App  │──────▶│  GraphQL API  │
└───────────────┘       └───────────────┘
       ▲                      ▲
       │                      │
  Refetch: Manual          Polling: Automatic
  request triggered       requests at intervals
  by user or event        (e.g., every 5 seconds)
Build-Up - 7 Steps
1
FoundationBasic GraphQL Query Fetching
🤔
Concept: Learn how to fetch data once using a GraphQL query.
A GraphQL query asks the server for specific data. For example, to get a list of books: query { books { title author } } This returns the current list of books once when the query runs.
Result
The app receives the list of books with their titles and authors one time.
Understanding how to fetch data once is the base for knowing why and when you might want to fetch it again.
2
FoundationWhy Data Becomes Stale
🤔
Concept: Data fetched once can become outdated as the real world changes.
Imagine you fetched a list of online users. If someone logs in or out after your fetch, your data is no longer accurate. Without updating, the app shows old information.
Result
The app may display incorrect or outdated data after some time.
Knowing that data changes over time explains why refetching or polling is needed to keep data fresh.
3
IntermediateManual Refetching in GraphQL
🤔Before reading on: do you think refetching happens automatically or only when triggered? Commit to your answer.
Concept: Refetching means manually asking the server for data again, usually triggered by user actions or events.
In GraphQL clients like Apollo, you can call a refetch function to run the query again: const { data, refetch } = useQuery(GET_BOOKS); // When user clicks refresh button This updates the data by fetching it again from the server.
Result
The app updates the displayed data when the user triggers refetching.
Understanding manual refetching helps control when data updates happen, avoiding unnecessary network requests.
4
IntermediateAutomatic Polling Setup
🤔Before reading on: do you think polling requests happen continuously or just once? Commit to your answer.
Concept: Polling automatically sends the same query repeatedly at set time intervals to keep data updated.
In Apollo Client, you can enable polling by setting a pollInterval: const { data } = useQuery(GET_BOOKS, { pollInterval: 5000 }); This runs the query every 5 seconds, updating data automatically without user action.
Result
The app refreshes data every 5 seconds, showing the latest information continuously.
Knowing how polling works helps build apps that stay updated without user effort, but also teaches to balance frequency to avoid overload.
5
IntermediatePolling vs Refetching Differences
🤔
Concept: Understand when to use manual refetching versus automatic polling based on app needs.
Refetching is good for on-demand updates, like when a user clicks refresh. Polling is better for data that changes often and needs constant updates, like live scores. Polling can cause extra network traffic if too frequent. Refetching gives more control but requires user or event triggers.
Result
You can choose the right method to keep data fresh efficiently.
Knowing the tradeoffs between polling and refetching helps optimize app performance and user experience.
6
AdvancedHandling Polling Side Effects
🤔Before reading on: do you think polling always updates the UI smoothly or can it cause flickers? Commit to your answer.
Concept: Polling can cause UI flickers or performance issues if not handled carefully.
When polling updates data, the UI may re-render frequently, causing flickers or slowdowns. To avoid this, use techniques like: - Comparing new data with old before updating UI - Pausing polling when the app is inactive - Adjusting poll intervals dynamically Example in Apollo: const { data, startPolling, stopPolling } = useQuery(GET_BOOKS); // Stop polling when tab is hidden useEffect(() => { const handleVisibility = () => { if (document.hidden) stopPolling(); else startPolling(5000); }; document.addEventListener('visibilitychange', handleVisibility); return () => document.removeEventListener('visibilitychange', handleVisibility); }, []);
Result
Polling runs efficiently without harming user experience or wasting resources.
Understanding polling side effects helps build smooth, resource-friendly apps.
7
ExpertOptimizing Polling with Cache and Network Policies
🤔Before reading on: do you think polling always fetches fresh data from the server or can it use cached data? Commit to your answer.
Concept: Advanced clients let you control how polling interacts with cache and network to optimize performance.
Apollo Client allows setting fetchPolicy to control data source: useQuery(GET_BOOKS, { pollInterval: 5000, fetchPolicy: 'network-only' // always fetch fresh data }); Or use 'cache-and-network' to show cached data immediately and update when network responds. This balances speed and freshness, reducing flickers and unnecessary requests. Also, you can combine polling with subscriptions for hybrid real-time updates.
Result
Polling is optimized to reduce latency and network load while keeping data fresh.
Knowing how to tune cache and network policies with polling unlocks expert-level performance and user experience.
Under the Hood
Refetching triggers a new GraphQL query request to the server, ignoring cached data if configured. Polling sets a timer that repeatedly triggers these requests at fixed intervals. The client manages these timers and updates the UI when new data arrives. Internally, the client merges new data with existing cache and triggers re-renders only if data changed.
Why designed this way?
Refetching and polling were designed to solve the problem of stale data in client-server apps before real-time subscriptions were widely supported. Polling is simple and works everywhere but can be inefficient. Refetching gives control to the app or user. These methods balance freshness and resource use given network and server constraints.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Client App  │──────▶│ GraphQL Client│──────▶│  GraphQL API  │
│               │       │ (cache, timers)│       │               │
└───────────────┘       └───────────────┘       └───────────────┘
       ▲                      ▲                      ▲
       │                      │                      │
   User triggers          Polling timer          Server processes
   refetch manually      triggers queries       and returns data
Myth Busters - 4 Common Misconceptions
Quick: Does polling always guarantee real-time data updates? Commit yes or no.
Common Belief:Polling always provides real-time data updates just like subscriptions.
Tap to reveal reality
Reality:Polling updates data only at fixed intervals, so it can miss changes between polls and is not truly real-time.
Why it matters:Relying on polling for real-time needs can cause delays and outdated information, hurting user experience.
Quick: Is refetching automatic or manual? Commit your answer.
Common Belief:Refetching happens automatically without any triggers.
Tap to reveal reality
Reality:Refetching is manual and only happens when the app or user explicitly requests it.
Why it matters:Assuming refetching is automatic can lead to apps showing stale data unexpectedly.
Quick: Does polling always increase network load significantly? Commit yes or no.
Common Belief:Polling always causes heavy network traffic and should be avoided.
Tap to reveal reality
Reality:Polling frequency and cache policies can be tuned to balance freshness and network load effectively.
Why it matters:Avoiding polling altogether may limit app responsiveness; proper tuning is key.
Quick: Can polling cause UI flickers? Commit yes or no.
Common Belief:Polling updates are seamless and never cause UI issues.
Tap to reveal reality
Reality:Frequent polling can cause UI flickers or performance drops if updates are not handled carefully.
Why it matters:Ignoring UI effects of polling can degrade user experience and app quality.
Expert Zone
1
Polling intervals should adapt based on user activity or network conditions to optimize resource use.
2
Combining polling with cache policies like 'cache-and-network' can reduce perceived latency while keeping data fresh.
3
Refetching can be combined with optimistic UI updates to improve responsiveness before server confirmation.
When NOT to use
Avoid polling for highly dynamic data where true real-time updates are needed; use GraphQL subscriptions instead. Refetching is not suitable for data that must update continuously without user action. For static or rarely changing data, rely on caching without polling to save resources.
Production Patterns
In production, polling is often used for dashboards or status pages with moderate update frequency. Refetching is common in forms or user-triggered refreshes. Experts combine polling with visibility APIs to pause updates when the app is in the background, saving battery and bandwidth.
Connections
GraphQL Subscriptions
Builds-on
Understanding polling and refetching prepares you to grasp subscriptions, which provide real-time updates by pushing data from server to client.
Caching Strategies
Builds-on
Knowing how polling interacts with cache policies helps optimize data freshness and performance in client apps.
Event-driven Systems (Software Engineering)
Similar pattern
Polling mimics event listening by repeatedly checking for changes, similar to how some event-driven systems poll resources before true event notifications existed.
Common Pitfalls
#1Polling too frequently causing network overload.
Wrong approach:useQuery(GET_DATA, { pollInterval: 100 }); // polls every 100ms
Correct approach:useQuery(GET_DATA, { pollInterval: 5000 }); // polls every 5 seconds
Root cause:Misunderstanding that very frequent polling improves freshness without considering network and performance costs.
#2Refetching without user trigger causing unexpected data reloads.
Wrong approach:useEffect(() => { refetch(); }, []); // refetch runs once on mount without user action
Correct approach:// Refetch only on user action
Root cause:Confusing automatic data fetching with manual refetching triggers.
#3Ignoring UI flickers during polling updates.
Wrong approach:const { data } = useQuery(GET_DATA, { pollInterval: 1000 }); // no UI update control
Correct approach:Use cache policies and compare data before updating UI to prevent flickers.
Root cause:Not handling frequent data updates carefully in UI rendering logic.
Key Takeaways
Refetching and polling keep GraphQL app data fresh by requesting updates from the server.
Refetching is manual and triggered by user or events; polling is automatic at set intervals.
Polling frequency and cache policies must be balanced to avoid performance and network issues.
Advanced use includes pausing polling when inactive and combining with caching for smooth UI.
Understanding these techniques prepares you for real-time subscriptions and efficient data handling.

Practice

(1/5)
1. What is the main purpose of refetching in GraphQL?
easy
A. To manually update data by running the query again
B. To automatically update data at regular intervals
C. To cache data locally for faster access
D. To delete outdated data from the server

Solution

  1. Step 1: Understand refetching concept

    Refetching means running the same query again to get fresh data when needed.
  2. Step 2: Compare with polling

    Polling updates data automatically, but refetching is manual and on demand.
  3. Final Answer:

    To manually update data by running the query again -> Option A
  4. Quick Check:

    Refetching = manual update [OK]
Hint: Refetching means manual data update by rerunning query [OK]
Common Mistakes:
  • Confusing refetching with automatic polling
  • Thinking refetching caches data
  • Assuming refetching deletes data
2. Which of the following is the correct way to enable polling every 5 seconds in a GraphQL query using Apollo Client?
easy
A. useQuery(MY_QUERY, { refetchInterval: 5000 })
B. useQuery(MY_QUERY, { refreshRate: 5 })
C. useQuery(MY_QUERY, { pollInterval: 5000 })
D. useQuery(MY_QUERY, { autoPoll: true, interval: 5000 })

Solution

  1. Step 1: Recall Apollo Client polling syntax

    Polling is enabled by setting pollInterval in milliseconds.
  2. Step 2: Check options for correctness

    Only useQuery(MY_QUERY, { pollInterval: 5000 }) uses the correct property pollInterval with 5000 ms (5 seconds).
  3. Final Answer:

    useQuery(MY_QUERY, { pollInterval: 5000 }) -> Option C
  4. Quick Check:

    pollInterval = 5000 ms [OK]
Hint: pollInterval sets polling time in ms in Apollo Client [OK]
Common Mistakes:
  • Using wrong property names like refetchInterval
  • Confusing seconds with milliseconds
  • Assuming autoPoll is a valid option
3. Given this code snippet using Apollo Client:
const { data, loading, refetch } = useQuery(GET_USERS, { pollInterval: 10000 });
setTimeout(() => refetch(), 5000);

What will happen regarding data updates?
medium
A. Data updates every 10 seconds only
B. Data updates at 5 seconds and then every 10 seconds
C. Data updates every 5 seconds only
D. Data updates only once at 5 seconds

Solution

  1. Step 1: Understand polling behavior

    Polling updates data automatically every 10 seconds as set by pollInterval.
  2. Step 2: Understand manual refetch

    The setTimeout calls refetch() once after 5 seconds, triggering an immediate update.
  3. Step 3: Combine effects

    So data updates at 5 seconds manually, then continues updating every 10 seconds automatically.
  4. Final Answer:

    Data updates at 5 seconds and then every 10 seconds -> Option B
  5. Quick Check:

    Manual refetch + polling = updates at 5s and every 10s [OK]
Hint: Manual refetch triggers immediate update, polling continues regularly [OK]
Common Mistakes:
  • Ignoring manual refetch timing
  • Assuming polling stops after manual refetch
  • Confusing polling interval with refetch delay
4. You wrote this code to poll data every 3 seconds:
const { data, loading } = useQuery(GET_POSTS, { pollInterval: 3000 });

But data is not updating automatically. What is the likely cause?
medium
A. The component is unmounted or paused
B. The pollInterval value is too low
C. The query is missing a refetch call
D. Polling requires manual trigger each time

Solution

  1. Step 1: Understand polling requirements

    Polling runs only when the component is mounted and active.
  2. Step 2: Check common issues

    If data is not updating, the component might be unmounted or React Suspense is pausing it.
  3. Step 3: Eliminate other options

    Polling does not need manual refetch, and 3000 ms is valid.
  4. Final Answer:

    The component is unmounted or paused -> Option A
  5. Quick Check:

    Polling requires active component [OK]
Hint: Polling only works if component is mounted and active [OK]
Common Mistakes:
  • Thinking polling needs manual refetch
  • Assuming pollInterval too low stops polling
  • Ignoring component lifecycle
5. You want to keep a chat app's messages updated. You use polling every 15 seconds but also want users to refresh manually. Which approach best combines refetching and polling?
hard
A. Use polling with pollInterval: 15000 and disable manual refresh
B. Use only refetching triggered by a button every 15 seconds
C. Use refetching inside a setInterval instead of polling
D. Use polling with pollInterval: 15000 and add a button that calls refetch()

Solution

  1. Step 1: Understand polling and manual refresh

    Polling updates data automatically every 15 seconds.
  2. Step 2: Add manual refresh

    Adding a button that calls refetch() lets users update data on demand.
  3. Step 3: Evaluate options

    Use polling with pollInterval: 15000 and add a button that calls refetch() combines both correctly; others either disable manual refresh or misuse refetching.
  4. Final Answer:

    Use polling with pollInterval: 15000 and add a button that calls refetch() -> Option D
  5. Quick Check:

    Polling + manual refetch button = best combo [OK]
Hint: Combine pollInterval with refetch button for best updates [OK]
Common Mistakes:
  • Using only manual refetch without polling
  • Disabling manual refresh when polling is active
  • Replacing polling with setInterval refetch