JavaScript and React course ยท Module 8: Advanced React Patterns
Adapter and Facade Patterns
In this lesson4
On our cosmic journey through React, our ship must connect with many different systems - space stations, satellites, planetary bases. Each of these systems has its own communication protocol. The Adapter and Facade patterns are like a universal translator that allows our ship to communicate with any system without needing to know its internal details.
Adapter Pattern
What is an Adapter?
The Adapter pattern (also known as Wrapper) allows objects with incompatible interfaces to work together. In React, we most commonly use it to wrap external APIs with a consistent, predictable interface.
Imagine that your cosmic weather database for different planets uses three different API providers. Each of them returns data in a different format. An Adapter allows you to unify this data:
// Raw responses from different space APIs
// Mars API returns: { temp_celsius: -60, wind_kph: 25, condition: "dusty" }
// Jupiter API returns: { temperature: { value: -145, unit: "C" }, windSpeed: 350 }
// Saturn API returns: { readings: { t: -178, w: 500 }, status: "stormy" }Without an adapter, we would need to check in every component which API the data came from and process it accordingly. That leads to a mess!
Implementing an Adapter in React
Let's create adapters that unify data from different APIs:
// Unified weather data interface
// { planet, temperature, windSpeed, condition }
function adaptMarsWeather(rawData) {
return {
planet: 'Mars',
temperature: rawData.temp_celsius,
windSpeed: rawData.wind_kph,
condition: rawData.condition,
};
}
function adaptJupiterWeather(rawData) {
return {
planet: 'Jupiter',
temperature: rawData.temperature.value,
windSpeed: rawData.windSpeed,
condition: rawData.windSpeed > 300 ? 'extreme' : 'moderate',
};
}
function adaptSaturnWeather(rawData) {
return {
planet: 'Saturn',
temperature: rawData.readings.t,
windSpeed: rawData.readings.w,
condition: rawData.status,
};
}Now we have three simple functions, each of which takes raw data and returns an object with an identical structure. Our weather component can use this data without knowing where it came from:
function PlanetWeatherCard({ weatherData }) {
// weatherData ALWAYS has the same shape thanks to adapters
return (
<div className="weather-card">
<h3>{weatherData.planet}</h3>
<p>Temperature: {weatherData.temperature} C</p>
<p>Wind: {weatherData.windSpeed} km/h</p>
<p>Condition: {weatherData.condition}</p>
</div>
);
}Adapter as a Custom Hook
Adapters work great as custom hooks that wrap external libraries:
// Adapter for different space map libraries
function useSpaceMap(provider) {
const [map, setMap] = useState(null);
useEffect(() => {
let mapInstance;
if (provider === 'galactic-maps') {
// GalacticMaps library has its own API
mapInstance = new GalacticMaps.Chart('#map');
mapInstance.init({ zoom: 5 });
} else if (provider === 'star-atlas') {
// StarAtlas has a completely different API
mapInstance = StarAtlas.create(document.getElementById('map'), {
level: 5,
mode: '3d',
});
}
// We return a unified interface
setMap({
zoomIn: () => {
if (provider === 'galactic-maps') mapInstance.setZoom(mapInstance.getZoom() + 1);
else mapInstance.changeLevel(mapInstance.level + 1);
},
zoomOut: () => {
if (provider === 'galactic-maps') mapInstance.setZoom(mapInstance.getZoom() - 1);
else mapInstance.changeLevel(mapInstance.level - 1);
},
centerOn: (coords) => {
if (provider === 'galactic-maps') mapInstance.panTo(coords);
else mapInstance.focus({ x: coords.lat, y: coords.lng });
},
});
return () => {
if (provider === 'galactic-maps') mapInstance.destroy();
else mapInstance.dispose();
};
}, [provider]);
return map;
}Thanks to this hook, the component using the map doesn't need to know which library is being used underneath. If we wanted to change the map provider, we would only need to modify the hook - no component would change.
Facade Pattern
What is a Facade?
The Facade pattern provides a simplified interface to a complex subsystem. In React, we most commonly implement it as hooks that hide complicated logic behind a simple API.
Think of a spaceship's control panel. The pilot doesn't need to know the details of how each system works - they press the "Start engines" button and the entire complex process starts automatically. A Facade works exactly the same way.
Simple example: Hook as a Facade
Without a facade, a component has to manage many details itself:
// WITHOUT Facade - the component is overwhelmed with details
function MissionLauncher() {
const [fuel, setFuel] = useState(0);
const [systems, setSystems] = useState([]);
const [crewReady, setCrewReady] = useState(false);
const [countdown, setCountdown] = useState(null);
const [launchStatus, setLaunchStatus] = useState('idle');
const [errors, setErrors] = useState([]);
// Checking fuel
useEffect(() => {
fetchFuelLevel().then(setFuel);
}, []);
// Checking systems
useEffect(() => {
checkAllSystems().then(setSystems);
}, []);
// Countdown
useEffect(() => {
if (countdown !== null && countdown > 0) {
const timer = setTimeout(() => setCountdown(c => c - 1), 1000);
return () => clearTimeout(timer);
}
if (countdown === 0) {
executeLaunch().then(() => setLaunchStatus('launched'));
}
}, [countdown]);
const startLaunch = async () => {
if (fuel < 80) { setErrors(e => [...e, 'Not enough fuel']); return; }
if (!crewReady) { setErrors(e => [...e, 'Crew not ready']); return; }
const failedSystems = systems.filter(s => s.status !== 'ok');
if (failedSystems.length > 0) {
setErrors(e => [...e, 'Systems not operational']);
return;
}
setCountdown(10);
};
// ... rest of component with a huge amount of logic
}With a facade, we move all this logic into a hook:
// WITH Facade - the hook hides all the complexity
function useMissionLaunch() {
const [fuel, setFuel] = useState(0);
const [systems, setSystems] = useState([]);
const [crewReady, setCrewReady] = useState(false);
const [countdown, setCountdown] = useState(null);
const [status, setStatus] = useState('idle');
const [errors, setErrors] = useState([]);
useEffect(() => {
fetchFuelLevel().then(setFuel);
checkAllSystems().then(setSystems);
}, []);
useEffect(() => {
if (countdown !== null && countdown > 0) {
const timer = setTimeout(() => setCountdown(c => c - 1), 1000);
return () => clearTimeout(timer);
}
if (countdown === 0) {
executeLaunch().then(() => setStatus('launched'));
}
}, [countdown]);
const launch = () => {
const newErrors = [];
if (fuel < 80) newErrors.push('Not enough fuel');
if (!crewReady) newErrors.push('Crew not ready');
const failedSystems = systems.filter(s => s.status !== 'ok');
if (failedSystems.length > 0) newErrors.push('Systems not operational');
if (newErrors.length > 0) {
setErrors(newErrors);
return;
}
setCountdown(10);
setStatus('countdown');
};
const abort = () => {
setCountdown(null);
setStatus('aborted');
};
return {
// Simple, readable API
launch,
abort,
status,
countdown,
errors,
isReady: fuel >= 80 && crewReady && systems.every(s => s.status === 'ok'),
fuelLevel: fuel,
setCrewReady,
};
}
// The component is now clean and simple
function MissionLauncher() {
const mission = useMissionLaunch();
return (
<div>
<h1>Mission Launch</h1>
<p>Fuel: {mission.fuelLevel}%</p>
<p>Status: {mission.status}</p>
{mission.countdown !== null && <p>Countdown: {mission.countdown}</p>}
{mission.errors.map((err, i) => <p key={i} style={{color: 'red'}}>{err}</p>)}
<button onClick={mission.launch} disabled={!mission.isReady}>
Launch
</button>
<button onClick={mission.abort}>Abort</button>
</div>
);
}Facade for complex operations
Facade is particularly useful when you need to coordinate multiple operations:
function useCrewManagement(missionId) {
// Internally manages multiple data sources
const [crew, setCrew] = useState([]);
const [assignments, setAssignments] = useState({});
const [healthRecords, setHealthRecords] = useState({});
useEffect(() => {
Promise.all([
fetchCrew(missionId),
fetchAssignments(missionId),
fetchHealthRecords(missionId),
]).then(([crewData, assignData, healthData]) => {
setCrew(crewData);
setAssignments(assignData);
setHealthRecords(healthData);
});
}, [missionId]);
// Simple interface for the component
return {
crewMembers: crew.map(member => ({
...member,
role: assignments[member.id]?.role || 'Unassigned',
healthStatus: healthRecords[member.id]?.status || 'Unknown',
})),
assignRole: (memberId, role) => {
updateAssignment(missionId, memberId, role)
.then(() => setAssignments(prev => ({
...prev,
[memberId]: { ...prev[memberId], role },
})));
},
isCrewReady: crew.length > 0 && crew.every(m =>
assignments[m.id]?.role && healthRecords[m.id]?.status === 'fit'
),
};
}When to use Adapter vs Facade?
| Feature | Adapter | Facade |
|---|---|---|
| Purpose | Unify incompatible interfaces | Simplify a complex system |
| When | Multiple data sources with different formats | Complex logic to hide |
| In React | Wrapping external APIs/libraries | Custom hooks hiding complexity |
| Space analogy | Alien civilization language translator | Ship control panel |
Both patterns can be combined - a Facade can internally use adapters:
function useGalacticWeather(planets) {
// Facade: simplifies the interface
const [weather, setWeather] = useState({});
useEffect(() => {
const adapters = {
mars: adaptMarsWeather,
jupiter: adaptJupiterWeather,
saturn: adaptSaturnWeather,
};
// Adapter: unifies data from different APIs
Promise.all(
planets.map(planet =>
fetchWeather(planet).then(raw => adapters[planet](raw))
)
).then(results => {
const weatherMap = {};
results.forEach(w => { weatherMap[w.planet] = w; });
setWeather(weatherMap);
});
}, [planets]);
return {
getWeather: (planet) => weather[planet] || null,
isLoaded: Object.keys(weather).length === planets.length,
coldestPlanet: Object.values(weather)
.sort((a, b) => a.temperature - b.temperature)[0]?.planet || null,
};
}Summary
The Adapter and Facade patterns are essential tools in the arsenal of a cosmic React programmer:
- Adapter allows you to unify incompatible interfaces, which is crucial when integrating with multiple external APIs and libraries
- Facade simplifies complex subsystems, creating readable and easy-to-use hooks
- Both patterns increase code readability, simplify testing, and reduce coupling between components
Just as a universal power adapter allows a spaceship to connect to any docking station in the galaxy, the Adapter and Facade patterns allow our React components to work with any system without unnecessary complications.
Code for this lesson: App.jsx
import React, { useState, useEffect } from 'react';
// ============================================
// ADAPTER AND FACADE PATTERN
// ============================================
// --- ADAPTER: Unifying data from different planet APIs ---
// Simulating raw responses from different APIs
const rawMarsData = { temp_celsius: -60, wind_kph: 25, condition: 'dusty' };
const rawJupiterData = { temperature: { value: -145, unit: 'C' }, windSpeed: 350 };
const rawSaturnData = { readings: { t: -178, w: 500 }, status: 'stormy' };
// Adapters - each converts raw data into a common format
function adaptMarsWeather(raw) {
return {
planet: 'Mars',
temperature: raw.temp_celsius,
windSpeed: raw.wind_kph,
condition: raw.condition,
};
}
function adaptJupiterWeather(raw) {
return {
planet: 'Jupiter',
temperature: raw.temperature.value,
windSpeed: raw.windSpeed,
condition: raw.windSpeed > 300 ? 'extreme' : 'moderate',
};
}
function adaptSaturnWeather(raw) {
return {
planet: 'Saturn',
temperature: raw.readings.t,
windSpeed: raw.readings.w,
condition: raw.status,
};
}
// Component using the unified data
function PlanetWeatherCard({ weatherData }) {
const getConditionColor = (condition) => {
const colors = {
dusty: '#ff9800', extreme: '#f44336',
stormy: '#9c27b0', moderate: '#4caf50',
};
return colors[condition] || '#00d4ff';
};
return (
<div style={cardStyle}>
<h3 style={{ color: '#ffd700', marginBottom: '12px' }}>
{weatherData.planet}
</h3>
<p>Temperature: <strong>{weatherData.temperature} C</strong></p>
<p>Wind: <strong>{weatherData.windSpeed} km/h</strong></p>
<p>
Condition:{' '}
<span style={{ color: getConditionColor(weatherData.condition), fontWeight: 'bold' }}>
{weatherData.condition}
</span>
</p>
</div>
);
}
// --- FACADE: Hook hiding complexity ---
function useGalacticWeather() {
const [weather, setWeather] = useState([]);
const [loading, setLoading] = useState(true);
const [selectedPlanet, setSelectedPlanet] = useState(null);
useEffect(() => {
// The facade hides all the logic for fetching and adapting data
const timer = setTimeout(() => {
const adapted = [
adaptMarsWeather(rawMarsData),
adaptJupiterWeather(rawJupiterData),
adaptSaturnWeather(rawSaturnData),
];
setWeather(adapted);
setLoading(false);
}, 800);
return () => clearTimeout(timer);
}, []);
// A simple interface for the component
return {
weather,
loading,
selectedPlanet: selectedPlanet
? weather.find(w => w.planet === selectedPlanet)
: null,
selectPlanet: setSelectedPlanet,
coldestPlanet: weather.length > 0
? weather.reduce((a, b) => a.temperature < b.temperature ? a : b).planet
: null,
averageTemp: weather.length > 0
? Math.round(weather.reduce((sum, w) => sum + w.temperature, 0) / weather.length)
: 0,
};
}
// --- Main application ---
function App() {
const {
weather, loading, selectedPlanet,
selectPlanet, coldestPlanet, averageTemp,
} = useGalacticWeather();
return (
<div style={appStyle}>
<h1 style={{ color: '#00d4ff', textAlign: 'center', marginBottom: '8px' }}>
Adapter and Facade - Weather in the galaxy
</h1>
<p style={{ textAlign: 'center', color: '#aaa', marginBottom: '24px' }}>
Data from 3 different APIs, unified by Adapters, simplified by Facade
</p>
{loading ? (
<p style={{ textAlign: 'center', color: '#ffd700' }}>Connecting to probes...</p>
) : (
<>
<div style={statsStyle}>
<span>Coldest: <strong style={{ color: '#00d4ff' }}>{coldestPlanet}</strong></span>
<span>Average temp: <strong style={{ color: '#ff9800' }}>{averageTemp} C</strong></span>
</div>
<div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', justifyContent: 'center' }}>
{weather.map(w => (
<div
key={w.planet}
onClick={() => selectPlanet(w.planet)}
style={{ cursor: 'pointer', flex: '1', minWidth: '200px' }}
>
<PlanetWeatherCard weatherData={w} />
</div>
))}
</div>
{selectedPlanet && (
<div style={{ ...cardStyle, marginTop: '20px', borderColor: '#ffd700' }}>
<h3 style={{ color: '#ffd700' }}>Details: {selectedPlanet.planet}</h3>
<p>Temperature: {selectedPlanet.temperature} C</p>
<p>Wind: {selectedPlanet.windSpeed} km/h</p>
<p>Conditions: {selectedPlanet.condition}</p>
<button
onClick={() => selectPlanet(null)}
style={btnStyle}
>
Close
</button>
</div>
)}
{/* TODO: Add a new planet (e.g. Neptune) with its own raw data format
and write an adapter for it. Neptune's raw format:
{ metrics: { tempC: -214, windMs: 580 }, weather: 'icy' }
The adapter should convert windMs to km/h (x 3.6) */}
</>
)}
</div>
);
}
const appStyle = {
background: '#0d1b2a', minHeight: '100vh', padding: '20px',
fontFamily: 'Arial, sans-serif', color: '#e0e1dd',
};
const cardStyle = {
background: '#1b2838', borderRadius: '12px', padding: '20px',
border: '1px solid #2a3f5f',
};
const statsStyle = {
display: 'flex', justifyContent: 'center', gap: '30px',
marginBottom: '20px', padding: '12px',
background: '#1b2838', borderRadius: '8px',
};
const btnStyle = {
marginTop: '10px', padding: '8px 20px', background: '#ff9800',
color: '#000', border: 'none', borderRadius: '6px',
cursor: 'pointer', fontWeight: 'bold',
};
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Horizontal ordering
Arrange the correct lazy loading component syntax: