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
Synchronizing with External Systems and Subscriptions0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
2.1Race Conditions and Stale Closures in useEffect2.2Synchronizing with External Systems and Subscriptions2.3Removing Unnecessary useEffect Hooks2.4Lifecycle Equivalents: Mount, Update, and Unmount
HomeTutorialsReact.js for IntermediateSynchronizing with External Systems and Subscriptions
Removing Unnecessary useEffect Hooks

Synchronizing with External Systems and Subscriptions

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

1. What is Synchronization in React?

The fundamental mental model of useEffect is synchronization.

An effect's job is not simply to run code on "mount" or "unmount"; its true responsibility is to synchronize the React component with an external non-React system:

  • A browser WebSocket connection
  • A browser Geolocation or Online/Offline network watcher
  • A third-party non-React widget (e.g., a Leaflet map, a Chart.js canvas, or a Stripe payment element)
  • The native browser DOM (e.g. modal focus trapping)
1[React State / Props] ◄══════ Synchronize ══════► [External Non-React System]
2 (WebSocket / Canvas / Browser API)

2. Example: Synchronizing with Browser Online Status

Web applications often need to warn users when their internet connection drops. The browser emits native online and offline events on the window object:

1import React, { useState, useEffect } from 'react';
2 
3export default function NetworkStatusIndicator() {
4 const [isOnline, setIsOnline] = useState(navigator.onLine);
5 
6 useEffect(() => {
7 const handleOnline = () => setIsOnline(true);
8 const handleOffline = () => setIsOnline(false);
9 
10 // Synchronize: subscribe to browser events
11 window.addEventListener('online', handleOnline);
12 window.addEventListener('offline', handleOffline);
13 
14 // Teardown: unsubscribe when component unmounts
15 return () => {
16 window.removeEventListener('online', handleOnline);
17 window.removeEventListener('offline', handleOffline);
18 };
19 }, []); // Synchronize on mount, clean up on unmount
20 
21 return (
22 <div className={`status-banner ${isOnline ? 'online' : 'offline'}`}>
23 <span className="dot" />
24 {isOnline ? 'Connected to MSK Network' : 'Offline — Changes will sync when reconnected'}
25 </div>
26 );
27}

3. Example: Synchronizing with a Real-Time WebSocket Channel

When connecting to a live messaging or financial stock channel:

1import React, { useState, useEffect } from 'react';
2 
3export default function StockTicker({ symbol }) {
4 const [price, setPrice] = useState(null);
5 
6 useEffect(() => {
7 // 1. Establish connection to external WebSocket service
8 const socket = new WebSocket(`wss://stocks.example.com/live/${symbol}`);
9 
10 socket.onopen = () => {
11 console.log(`Subscribed to live ticker: ${symbol}`);
12 };
13 
14 socket.onmessage = (event) => {
15 const data = JSON.parse(event.data);
16 setPrice(data.currentPrice);
17 };
18 
19 socket.onerror = (err) => {
20 console.error('Socket error:', err);
21 };
22 
23 // 2. Teardown: Close the socket when 'symbol' changes or component unmounts!
24 return () => {
25 console.log(`Unsubscribing from: ${symbol}`);
26 socket.close();
27 };
28 }, [symbol]); // Re-synchronize whenever the stock symbol changes
29 
30 return (
31 <div className="ticker-card">
32 <h4>{symbol}</h4>
33 <p className="price-display">
34 {price !== null ? `$${price.toFixed(2)}` : 'Connecting...'}
35 </p>
36 </div>
37 );
38}

If the user switches from AAPL to GOOGL:

  1. 1
    React calls socket.close() on the AAPL socket.
  2. 2
    React opens a brand new WebSocket for GOOGL.

4. The Mental Model: Start and Stop

Every effect synchronizing with an external system should have symmetric Start and Stop logic:

  • addEventListener ↔ removeEventListener
  • socket.connect() ↔ socket.close()
  • observer.observe() ↔ observer.disconnect()
  • timer = setTimeout() ↔ clearTimeout(timer)

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary mental model of useEffect in modern React architecture?
Question 2
Why must socket.close() be invoked in the return cleanup function of a WebSocket effect?
Question 3
What happens when the symbol prop changes in the StockTicker component?
Question 4
Which pair of methods represents a correct symmetric setup and teardown for a native browser event?
Question 5
If a component only needs to read navigator.onLine on initial mount and listens for changes until unmounted, what should its dependency array be?
Next Lesson

Removing Unnecessary useEffect Hooks

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

Related Lessons

Previous LessonNext Lesson
Race Conditions and Stale Closures in useEffectRemoving Unnecessary useEffect Hooks

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 Intermediate 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