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
External Store Synchronization with useSyncExternalStore0%
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
7.1Concurrent Rendering with useTransition7.2Deferred Value Updates with useDeferredValue7.3Synchronous Layout Calculations with useLayoutEffect7.4External Store Synchronization with useSyncExternalStore
HomeTutorialsReact.js for AdvancedExternal Store Synchronization with useSyncExternalStore
Virtualizing Massive Lists with TanStack Virtual

External Store Synchronization with useSyncExternalStore

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

Prior to React 18, state management libraries (Redux, Zustand, MobX) relied on useEffect and useState to subscribe to external mutable stores. With the arrival of Concurrent React and interruptible rendering, this naive approach suffered from tearing: a visual bug where different components in the same tree render conflicting data from the same store because the store mutated midway through an interrupted render. useSyncExternalStore solves tearing with guaranteed synchronous consistency.


1. What is "Tearing"?

In graphics and UI development, tearing occurs when a frame displays data from two different points in time:

1Concurrent Render Timeline:
21. Component A renders with Store State: { count: 1 }
32. React pauses render to handle high-priority user click
43. External store mutates to: { count: 2 }
54. React resumes render: Component B renders with Store State: { count: 2 }
6RESULT: Component A displays "1", Component B displays "2" in the exact same view!

useSyncExternalStore guarantees that any external store subscription is read synchronously without tearing across the entire concurrent render.


2. API Signature

1const state = useSyncExternalStore(
2 subscribe,
3 getSnapshot,
4 getServerSnapshot // Optional: for SSR hydration
5);
  • subscribe(callback): Registers a listener that is invoked whenever the store mutates. Must return a cleanup unsubscribe function.
  • getSnapshot(): Returns an immutable snapshot of current store data. If the store hasn't changed, it must return the exact same referential value.
  • getServerSnapshot(): Returns the snapshot during SSR HTML rendering.

3. Subscribing to Browser APIs: window.navigator.onLine

A common use case is subscribing to native browser events without third-party libraries:

1import React, { useSyncExternalStore } from "react";
2 
3// 1. Subscribe function: attaches browser event listeners
4function subscribeOnlineStatus(callback: () => void) {
5 window.addEventListener("online", callback);
6 window.addEventListener("offline", callback);
7 
8 return () => {
9 window.removeEventListener("online", callback);
10 window.removeEventListener("offline", callback);
11 };
12}
13 
14// 2. Client snapshot getter
15function getOnlineSnapshot() {
16 return navigator.onLine;
17}
18 
19// 3. Server snapshot getter (default to true during SSR)
20function getServerSnapshot() {
21 return true;
22}
23 
24// Custom hook
25export function useOnlineStatus() {
26 return useSyncExternalStore(
27 subscribeOnlineStatus,
28 getOnlineSnapshot,
29 getServerSnapshot
30 );
31}
32 
33export function NetworkStatusBadge() {
34 const isOnline = useOnlineStatus();
35 
36 return (
37 <div className="p-4 bg-slate-900 text-white rounded-lg flex items-center gap-3">
38 <div className={`h-3 w-3 rounded-full ${isOnline ? "bg-emerald-500" : "bg-rose-500 animate-ping"}`} />
39 <span className="text-sm font-semibold">
40 {isOnline ? "Connected to Cloud Services" : "Offline: Check Network Connection"}
41 </span>
42 </div>
43 );
44}

4. Subscribing to Media Queries (window.matchMedia)

1import { useSyncExternalStore } from "react";
2 
3export function useMediaQuery(query: string) {
4 const subscribe = (callback: () => void) => {
5 const matchMediaList = window.matchMedia(query);
6 matchMediaList.addEventListener("change", callback);
7 return () => matchMediaList.removeEventListener("change", callback);
8 };
9 
10 const getSnapshot = () => window.matchMedia(query).matches;
11 const getServerSnapshot = () => false;
12 
13 return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
14}
15 
16// Usage:
17// const isMobile = useMediaQuery("(max-width: 768px)");

5. Critical Rule: Stable getSnapshot References

The function returned by getSnapshot must return a cached or primitive value. If getSnapshot returns a new object literal ({ count: store.count }) on every invocation, React detects an infinite change loop and crashes with:

"Maximum update depth exceeded."

Always return primitive types or referentially stable memoized slices from getSnapshot.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is "tearing" in Concurrent React?
Question 2
Which hook was introduced in React 18 specifically to eliminate tearing in external state libraries?
Question 3
What must the subscribe parameter passed to useSyncExternalStore return?
Question 4
Why must getSnapshot() return referentially identical values if the store has not changed?
Question 5
What is the purpose of the third argument (getServerSnapshot) in useSyncExternalStore?
Next Lesson

Virtualizing Massive Lists with TanStack Virtual

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

Related Lessons

Previous LessonNext Lesson
Synchronous Layout Calculations with useLayoutEffectVirtualizing Massive Lists with TanStack Virtual

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