JavaScript and React course · Module 5: useEffect and Custom Hooks
Synchronization with External Systems
In this lesson7
In the previous module, we learned the basics of side effects with the useEffect hook. Now we'll dive deeper into one of the most important use cases for effects: synchronizing React components with external systems and libraries.
Why is synchronization important?
React components exist in their own reactive environment, but they often need to interact with independent systems that are unaware of React's lifecycle or rendering model. You can think of this as a bridge between the React spaceship and other systems - communication must be bidirectional and reliable.
Examples of such external systems include:
- Map libraries (e.g., Google Maps, Leaflet)
- Chart libraries (e.g., D3.js, Chart.js)
- Media players (e.g., HTML5 Video, Web Audio API)
- WebSocket SDKs and real-time communication
- Form management systems (e.g., Formik, React Hook Form)
- Animation libraries (e.g., GSAP, Anime.js)
- Browser interfaces (geolocation, Web Bluetooth)
Basic synchronization pattern
The basic pattern for synchronization with an external system looks as follows:
- Initialize the external library/system after the first render
- Update the external system when relevant props or state change
- Clean up (stop, disconnect) when the component is unmounted
function ExternalSystemComponent({ config }) {
useEffect(() => {
// 1. Initialization
const externalInstance = new ExternalSystem(config);
externalInstance.initialize();
// 2. Update (optional)
externalInstance.update(config);
// 3. Cleanup
return () => {
externalInstance.cleanup();
};
}, [config]); // Re-synchronize when config changes
return <div className="external-system-container" />;
}Practical synchronization examples
1. Integration with a map library (Leaflet)
Leaflet is a popular library for interactive maps that works independently from React. Here's an integration example:
import React, { useEffect, useRef } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
function MarsExplorationMap({ missionCoordinates, roverPosition, zoom = 5 }) {
// Ref to the map container
const mapContainerRef = useRef(null);
// Ref to the map instance (to avoid re-creation)
const mapInstanceRef = useRef(null);
// Ref to the rover marker (to update only its position)
const roverMarkerRef = useRef(null);
// Map initialization
useEffect(() => {
if (!mapInstanceRef.current && mapContainerRef.current) {
// Create map instance only once
const mapInstance = L.map(mapContainerRef.current).setView(
[missionCoordinates.lat, missionCoordinates.lng],
zoom
);
// Add map layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(mapInstance);
// Save map instance in reference
mapInstanceRef.current = mapInstance;
// Add rover marker
roverMarkerRef.current = L.marker([roverPosition.lat, roverPosition.lng])
.addTo(mapInstance)
.bindPopup('Mars Rover');
}
// Cleanup function
return () => {
if (mapInstanceRef.current) {
// Remove map when component unmounts
mapInstanceRef.current.remove();
mapInstanceRef.current = null;
roverMarkerRef.current = null;
}
};
}, []); // Empty dependency array - initialize only once
// Update rover position
useEffect(() => {
if (roverMarkerRef.current && roverPosition) {
// Update the position of the existing marker
roverMarkerRef.current.setLatLng([roverPosition.lat, roverPosition.lng]);
}
}, [roverPosition]); // Update only when rover position changes
// Update zoom level
useEffect(() => {
if (mapInstanceRef.current) {
mapInstanceRef.current.setZoom(zoom);
}
}, [zoom]); // Update only when zoom changes
return <div ref={mapContainerRef} style={{ height: '500px', width: '100%' }} />;
}In the example above:
- We use references (useRef) to store DOM elements and external library instances
- We initialize the map only once and save its instance
- We use separate effects to handle different aspects of synchronization
- We clean up resources when the component is unmounted
2. Integration with a chart library (Chart.js)
Chart.js is a popular library for creating interactive charts:
import React, { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';
function MissionResourcesChart({ resources, title }) {
const chartRef = useRef(null);
const chartInstanceRef = useRef(null);
useEffect(() => {
// Make sure we have access to the canvas element
if (!chartRef.current) return;
// Get canvas context
const ctx = chartRef.current.getContext('2d');
// Destroy previous chart instance if it exists
if (chartInstanceRef.current) {
chartInstanceRef.current.destroy();
}
// Create new chart instance
chartInstanceRef.current = new Chart(ctx, {
type: 'bar',
data: {
labels: resources.map(resource => resource.name),
datasets: [{
label: title || 'Mission Resources',
data: resources.map(resource => resource.level),
backgroundColor: resources.map(resource => {
// Color bars based on resource level
if (resource.level < 20) return 'rgba(255, 0, 0, 0.7)'; // Critical
if (resource.level < 50) return 'rgba(255, 165, 0, 0.7)'; // Warning
return 'rgba(0, 128, 0, 0.7)'; // OK
}),
borderColor: 'rgba(0, 0, 0, 0.1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
max: 100
}
}
}
});
// Cleanup
return () => {
if (chartInstanceRef.current) {
chartInstanceRef.current.destroy();
chartInstanceRef.current = null;
}
};
}, [resources, title]); // Recreate chart when data or title changes
return <canvas ref={chartRef} />;
}3. Handling Web Sockets
Web Socket integration enables real-time communication:
import React, { useEffect, useState } from 'react';
function MissionControlSocket({ missionId, onMessage }) {
const [status, setStatus] = useState('disconnected');
const [error, setError] = useState(null);
useEffect(() => {
// Socket initialization
const socket = new WebSocket(`wss://mission-control.example.com/ws/${missionId}`);
// Event configuration
socket.onopen = () => {
setStatus('connected');
console.log(`Connected to mission ${missionId}`);
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
onMessage(data);
};
socket.onerror = (err) => {
setStatus('error');
setError('Connection error with mission control center');
console.error('WebSocket error:', err);
};
socket.onclose = () => {
setStatus('disconnected');
console.log('Connection closed');
};
// Cleanup function
return () => {
// Close connection on unmount
if (socket.readyState === WebSocket.OPEN) {
socket.close();
}
};
}, [missionId, onMessage]); // Reconnect when missionId changes
return (
<div className="mission-socket">
<div className={`connection-status ${status}`}>
Connection status: {status}
</div>
{error && <div className="connection-error">{error}</div>}
</div>
);
}Strategies for efficient synchronization
1. Minimizing re-initializations
Avoid unnecessarily re-initializing external systems when only part of the configuration changes. Instead:
- Use separate effects for different aspects of synchronization
- Use references to store instances of external libraries
- Update existing instances instead of creating new ones
// BAD - single effect re-initializes everything
useEffect(() => {
const chart = new ChartLibrary(config);
return () => chart.destroy();
}, [config]); // Every change in config causes re-initialization
// GOOD - separate initialization and update
// Ref to store instance
const chartRef = useRef(null);
// Initialize only once
useEffect(() => {
chartRef.current = new ChartLibrary(containerRef.current);
return () => chartRef.current.destroy();
}, []);
// Update configuration without re-initialization
useEffect(() => {
if (chartRef.current) {
chartRef.current.updateConfig(config);
}
}, [config]);2. Managing subscriptions
When working with external data sources that use subscriptions:
- Always cancel subscriptions in the cleanup function
- Update subscriptions when parameters change
function TelemetryMonitor({ satelliteId, dataType }) {
const [data, setData] = useState(null);
useEffect(() => {
// Create subscription
const subscription = telemetryAPI.subscribe(
satelliteId,
dataType,
(newData) => setData(newData)
);
// Cleanup
return () => subscription.unsubscribe();
}, [satelliteId, dataType]); // Re-subscribe when ID or data type changes
return <div>{/* Rendering data */}</div>;
}3. Lazy initialization of resource-heavy libraries
For heavy external libraries, you can delay their initialization until they are actually needed:
function HeavyChart({ data, shouldRender }) {
const [chartInstance, setChartInstance] = useState(null);
const containerRef = useRef(null);
// Lazy initialization
useEffect(() => {
if (!shouldRender) {
// Don't initialize if we shouldn't render yet
return;
}
// Dynamic import of heavy library
import('heavy-chart-library').then(ChartLib => {
const instance = new ChartLib.Chart(containerRef.current, data);
setChartInstance(instance);
return () => {
instance.destroy();
};
});
}, [shouldRender]); // Run only when shouldRender changes to true
// Update data
useEffect(() => {
if (chartInstance && data) {
chartInstance.updateData(data);
}
}, [chartInstance, data]);
return <div ref={containerRef} />;
}Creating custom hooks for synchronization
To improve code reuse and encapsulate synchronization logic, it's worth creating custom hooks.
Example: Custom hook for map integration
function useLeafletMap(containerRef, initialConfig) {
const mapRef = useRef(null);
const [isReady, setIsReady] = useState(false);
// Initialization
useEffect(() => {
if (!containerRef.current || mapRef.current) return;
const map = L.map(containerRef.current, initialConfig);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
mapRef.current = map;
setIsReady(true);
return () => {
map.remove();
mapRef.current = null;
setIsReady(false);
};
}, [containerRef, initialConfig]);
// Methods for manipulating the map
const setView = useCallback((center, zoom) => {
if (mapRef.current) {
mapRef.current.setView(center, zoom);
}
}, []);
const addMarker = useCallback((position, options = {}) => {
if (!mapRef.current) return null;
const marker = L.marker(position, options).addTo(mapRef.current);
return marker;
}, []);
return {
map: mapRef.current,
isReady,
setView,
addMarker
};
}
// Using the custom hook
function MarsMap() {
const containerRef = useRef(null);
const { map, isReady, setView, addMarker } = useLeafletMap(
containerRef,
{ center: [24.7136, 46.6753], zoom: 5 }
);
// Add marker after map loads
useEffect(() => {
if (isReady) {
const marker = addMarker([24.7136, 46.6753], { title: 'Base Alpha' });
marker.bindPopup('Base Alpha - Main colony on Mars').openPopup();
}
}, [isReady, addMarker]);
return (
<div>
<h2>Mars Colony Map</h2>
<div ref={containerRef} style={{ height: '500px' }} />
{!isReady && <div>Loading map...</div>}
</div>
);
}Example: Custom hook for local storage
function useLocalStorage(key, initialValue) {
// State initializer function - runs only once
const [storedValue, setStoredValue] = useState(() => {
try {
// Check if localStorage is available
if (typeof window === 'undefined') {
return initialValue;
}
// Try to get value from localStorage
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error('Error reading from localStorage:', error);
return initialValue;
}
});
// Function to update value in localStorage
const setValue = useCallback((value) => {
try {
// Support function as value (like in setState)
const valueToStore = value instanceof Function ? value(storedValue) : value;
// Update React state
setStoredValue(valueToStore);
// Update localStorage
if (typeof window !== 'undefined') {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.error('Error writing to localStorage:', error);
}
}, [key, storedValue]);
// Synchronize with localStorage when key changes
useEffect(() => {
// Get current value for new key
try {
if (typeof window === 'undefined') return;
const item = window.localStorage.getItem(key);
setStoredValue(item ? JSON.parse(item) : initialValue);
} catch (error) {
console.error('Error synchronizing with localStorage:', error);
}
}, [key, initialValue]);
return [storedValue, setValue];
}
// Using the custom hook
function AstronautSettings() {
const [settings, setSettings] = useLocalStorage('astronaut-settings', {
oxygenAlert: 20,
darkMode: false,
notifications: true
});
const toggleDarkMode = () => {
setSettings(prev => ({
...prev,
darkMode: !prev.darkMode
}));
};
return (
<div className={settings.darkMode ? 'dark-theme' : 'light-theme'}>
<h2>Astronaut Settings</h2>
<button onClick={toggleDarkMode}>
Switch to {settings.darkMode ? 'light' : 'dark'} mode
</button>
<div>
Oxygen level alert: {settings.oxygenAlert}%
<input
type="range"
min="5"
max="50"
value={settings.oxygenAlert}
onChange={e => setSettings({
...settings,
oxygenAlert: Number(e.target.value)
})}
/>
</div>
<label>
<input
type="checkbox"
checked={settings.notifications}
onChange={() => setSettings(prev => ({
...prev,
notifications: !prev.notifications
}))}
/>
Enable notifications
</label>
</div>
);
}Handling effects in tests
Testing components that synchronize with external systems requires a special approach:
- Mocking external libraries
- Testing cleanup functions
- Verifying that synchronization works correctly
Example test for a WebSocket component:
import { render, act, screen, waitFor } from '@testing-library/react';
import MissionControlSocket from './MissionControlSocket';
// Mock for WebSocket
class MockWebSocket {
constructor(url) {
this.url = url;
this.readyState = WebSocket.CONNECTING;
// Auto "connect" after creation
setTimeout(() => {
this.readyState = WebSocket.OPEN;
this.onopen && this.onopen();
}, 0);
}
// Methods for simulating external events
simulateMessage(data) {
this.onmessage && this.onmessage({ data: JSON.stringify(data) });
}
simulateError() {
this.onerror && this.onerror(new Error('Test error'));
}
simulateClose() {
this.readyState = WebSocket.CLOSED;
this.onclose && this.onclose();
}
close() {
this.simulateClose();
}
}
// Replace global WebSocket class
global.WebSocket = MockWebSocket;
describe('MissionControlSocket', () => {
test('should connect to WebSocket and handle messages', async () => {
const mockOnMessage = jest.fn();
render(
<MissionControlSocket
missionId="apollo11"
onMessage={mockOnMessage}
/>
);
// Wait for connection
await waitFor(() => {
expect(screen.getByText(/connection status: connected/i)).toBeInTheDocument();
});
// Simulate receiving a message
const testData = { type: 'telemetry', oxygen: 95, fuel: 76 };
act(() => {
// Access WebSocket instance through monkeypatching
const socket = global.WebSocket.instances[0];
socket.simulateMessage(testData);
});
// Check if callback was called with appropriate data
expect(mockOnMessage).toHaveBeenCalledWith(testData);
// Simulate error
act(() => {
const socket = global.WebSocket.instances[0];
socket.simulateError();
});
// Check if error status is visible
expect(screen.getByText(/connection status: error/i)).toBeInTheDocument();
expect(screen.getByText(/connection error/i)).toBeInTheDocument();
});
test('should clean up WebSocket connection on unmount', () => {
const { unmount } = render(
<MissionControlSocket missionId="apollo11" onMessage={() => {}} />
);
// Get WebSocket instance
const socket = global.WebSocket.instances[0];
const closeSpy = jest.spyOn(socket, 'close');
// Unmount the component
unmount();
// Check if socket was closed
expect(closeSpy).toHaveBeenCalled();
});
});Summary
Synchronization with external systems is one of the most important functions of the useEffect hook. It enables the use of existing libraries and APIs within the React ecosystem while maintaining the reactive update model.
Key principles:
- Initialize external systems after the first render
- Update them when relevant data changes
- Clean up resources when the component is unmounted
- Separate effects by their responsibility
- Encapsulate synchronization logic in dedicated hooks
- Minimize unnecessary re-initializations
- Test the correctness of synchronization and cleanup
Remember that the main goal of synchronization is to maintain consistency between the reactive world of React and external systems that know nothing about the component lifecycle. With proper synchronization, your application will work smoothly and efficiently, connecting different technologies into one cohesive whole.
Code for this lesson: App.jsx
import React, { useState, useEffect, useRef } from 'react';
// Synchronization with an external API - space navigation system
function SpaceNavigationSystem() {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isTracking, setIsTracking] = useState(true);
const [lastSync, setLastSync] = useState(null);
// Synchronization with an "external" navigation system
useEffect(() => {
if (!isTracking) return;
// Simulating an external navigation system
const interval = setInterval(() => {
setPosition(prev => ({
x: prev.x + (Math.random() - 0.5) * 10,
y: prev.y + (Math.random() - 0.5) * 10
}));
setLastSync(new Date().toLocaleTimeString());
}, 1000);
// Cleanup - disconnecting from the system
return () => {
console.log('Disconnecting from navigation system...');
clearInterval(interval);
};
}, [isTracking]);
return (
<div className="nav-system">
<h2>Space Navigation System</h2>
<div className="status">
Status: {isTracking ? 'Active' : 'Inactive'}
</div>
<div className="coordinates">
<p>Coordinate X: {position.x.toFixed(2)}</p>
<p>Coordinate Y: {position.y.toFixed(2)}</p>
</div>
{lastSync && <p className="sync-time">Last synchronization: {lastSync}</p>}
<button onClick={() => setIsTracking(!isTracking)}>
{isTracking ? 'Stop tracking' : 'Resume tracking'}
</button>
</div>
);
}
// Synchronization with DOM - external charting library
function ExternalChartSync() {
const chartRef = useRef(null);
const [data, setData] = useState([30, 50, 40, 60, 45, 70, 55]);
// Synchronization with an "external charting library"
useEffect(() => {
const canvas = chartRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
// Clearing the canvas
ctx.clearRect(0, 0, width, height);
// Drawing the chart
ctx.fillStyle = 'rgba(97, 218, 251, 0.3)';
ctx.strokeStyle = '#61dafb';
ctx.lineWidth = 2;
const barWidth = width / data.length - 10;
data.forEach((value, index) => {
const x = index * (barWidth + 10) + 5;
const barHeight = (value / 100) * height;
const y = height - barHeight;
ctx.fillRect(x, y, barWidth, barHeight);
ctx.strokeRect(x, y, barWidth, barHeight);
});
// Cleanup - clearing the canvas on unmount
return () => {
ctx.clearRect(0, 0, width, height);
};
}, [data]);
const updateData = () => {
setData(prev => prev.map(() => Math.random() * 100));
};
return (
<div className="chart-sync">
<h2>Canvas Synchronization</h2>
<canvas ref={chartRef} width={350} height={200} />
<button onClick={updateData}>Refresh data</button>
</div>
);
}
// Synchronization with WebSocket (simulation)
function WebSocketSync() {
const [messages, setMessages] = useState([]);
const [connected, setConnected] = useState(false);
useEffect(() => {
// Simulating a WebSocket connection
console.log('Connecting to WebSocket...');
setConnected(true);
const interval = setInterval(() => {
const newMessage = {
id: Date.now(),
text: `Message from space #${Math.floor(Math.random() * 1000)}`,
time: new Date().toLocaleTimeString()
};
setMessages(prev => [...prev.slice(-4), newMessage]);
}, 2000);
// Cleanup - closing the connection
return () => {
console.log('Closing WebSocket connection...');
clearInterval(interval);
setConnected(false);
};
}, []);
return (
<div className="websocket-sync">
<h2>WebSocket Communication</h2>
<div className="connection-status">
{connected ? 'Connected' : 'Disconnected'}
</div>
<div className="messages">
{messages.map(msg => (
<div key={msg.id} className="message">
<span className="time">[{msg.time}]</span> {msg.text}
</div>
))}
</div>
</div>
);
}
function App() {
return (
<div className="app">
<h1>Synchronization with external systems</h1>
<div className="demos">
<SpaceNavigationSystem />
<ExternalChartSync />
<WebSocketSync />
</div>
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Vertical ordering
Order useEffect variants from most frequently to least frequently triggered:
- Code editor
Create [seconds, setSeconds] = useState(0). useEffect with setInterval every 1s: setSeconds(s => s + 1). IMPORTANT: return () => clearInterval(intervalId) - cleanup prevents memory leaks! Display: 'Mission time: {seconds}s'
- Vertical ordering
Order the stages of the effect lifecycle with a cleanup function:
- Click in order
Arrange the component structure with useEffect: