React
Beginner
1 min read
Synchronising with External Systems
Example
import { useEffect, useRef } from 'react';
// Imaginary third-party map library
// const map = new ThirdPartyMap(container, { zoom, center });
function MapWidget({ zoom, center }) {
const containerRef = useRef(null);
const mapRef = useRef(null);
// Create the map once on mount
useEffect(() => {
mapRef.current = new window.ThirdPartyMap(containerRef.current, {
zoom,
center,
});
return () => {
mapRef.current.destroy(); // cleanup
mapRef.current = null;
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// Synchronise zoom whenever it changes
useEffect(() => {
if (mapRef.current) {
mapRef.current.setZoom(zoom);
}
}, [zoom]);
// Synchronise center whenever it changes
useEffect(() => {
if (mapRef.current) {
mapRef.current.setCenter(center);
}
}, [center]);
return <div ref={containerRef} style={{ width: '100%', height: 400 }} />;
}