JavaScript and React course Β· Module 10: React Ecosystem and Future
Main Project: Space Mission Command Center
In this lesson6
Congratulations, astronaut! You have reached the final mission in the React Mastery module. It is time to combine all the technologies you have learned into one powerful system - the Space Mission Command Center. This project is your ultimate test to prove you have mastered advanced React patterns.
Project Goal
You will build a dashboard for managing a space mission that combines key concepts from the entire module:
1. React Portals - Modal Alert Windows
Use React Portals to render modal mission alert windows outside the main DOM tree. Alerts should appear above the interface with an overlay effect.
2. Internationalization (i18n)
Add a language switcher (PL/EN) to the header. The entire dashboard should change interface language dynamically using Context API and translation objects.
3. State Management with useReducer
Manage mission state (status, fuel, crew, systems) using useReducer. Define actions such as LAUNCH_MISSION, UPDATE_FUEL, TOGGLE_SYSTEM, ADD_CREW_MEMBER.
4. Compound Components
Create a <Dashboard.Panel> component using the Compound Components pattern that allows flexible composition of dashboard sections:
<Dashboard>
<Dashboard.Header title="Mission Control" />
<Dashboard.Panel title="Systems">
<SystemsList />
</Dashboard.Panel>
<Dashboard.Panel title="Crew">
<CrewList />
</Dashboard.Panel>
</Dashboard>5. Error Boundaries
Wrap dashboard sections in Error Boundaries so that a failure in one panel does not crash the entire application. Display a friendly error message with an option to reload the section.
6. Performance Optimization
Apply React.memo to list components, useMemo for mission statistics calculations, and useCallback for event handlers passed to child components.
Application Structure
Before you write the first line of code, sketch the component tree. The context providers sit at the very top so that every panel can read the language and the mission state, and every panel has its own Error Boundary, so one failing panel does not take down the others. The alert window renders through a portal, outside the dashboard tree:
App
βββ LanguageProvider (Context - i18n)
βββ MissionProvider (useReducer - state)
βββ Dashboard (Compound Component)
β βββ Dashboard.Header
β βββ Dashboard.Panel "Mission Status"
β β βββ ErrorBoundary
β β βββ MissionStatus (React.memo)
β βββ Dashboard.Panel "Systems"
β β βββ ErrorBoundary
β β βββ SystemsList (React.memo)
β βββ Dashboard.Panel "Crew"
β βββ ErrorBoundary
β βββ CrewList (React.memo)
βββ Portal -> AlertModal (React Portal)Requirements
- Dashboard displays 3 panels: Mission Status, Systems, Crew
- Language switcher (PL/EN) changes all interface labels
- "Launch Mission" button changes status and consumes fuel (useReducer)
- Systems can be toggled on/off
- Alert modal (Portal) appears when fuel drops below 20%
- Error Boundary displays fallback when a component throws an error
- Memoization prevents unnecessary re-renders
Implementation Hints
Reducer for Mission State
The whole mission state lives in one reducer, a pure function that computes the new state from the previous state and an action. It does not modify the state object, it returns a copy with updated fields, so React knows something changed, and React.memo can skip the panels whose data did not change:
const initialState = {
status: 'ready',
fuel: 100,
systems: [
{ id: 1, name: 'Navigation', active: true },
{ id: 2, name: 'Life Support', active: true },
{ id: 3, name: 'Communications', active: false },
],
crew: ['Kowalski', 'Nowak', 'Smith'],
};
function missionReducer(state, action) {
switch (action.type) {
case 'LAUNCH_MISSION':
return { ...state, status: 'inProgress', fuel: Math.max(0, state.fuel - 20) };
case 'UPDATE_FUEL':
return { ...state, fuel: Math.max(0, state.fuel + action.payload) };
case 'TOGGLE_SYSTEM':
return {
...state,
systems: state.systems.map(s =>
s.id === action.payload ? { ...s, active: !s.active } : s
),
};
case 'ADD_CREW_MEMBER':
return { ...state, crew: [...state.crew, action.payload] };
default:
return state;
}
}Components do not change the state themselves, they dispatch actions, for example dispatch({ type: 'TOGGLE_SYSTEM', payload: 2 }). Math.max makes sure the fuel never drops below zero.
Context for i18n
Translations are plain objects, one per language. The context provider keeps the current language in state and exposes the setLang function, and components read texts through their own useLanguage hook, so switching the language immediately redraws every label:
const translations = {
pl: { launch: 'Rozpocznij misjΔ', fuel: 'Paliwo', systems: 'Systemy' },
en: { launch: 'Launch Mission', fuel: 'Fuel', systems: 'Systems' },
};
const LanguageContext = createContext();
function LanguageProvider({ children }) {
const [lang, setLang] = useState('pl');
const t = translations[lang];
return (
<LanguageContext.Provider value={{ lang, setLang, t }}>
{children}
</LanguageContext.Provider>
);
}
function useLanguage() {
return useContext(LanguageContext);
}Portal for Alerts
The alert has to cover the whole interface, and a parent with overflow: hidden or its own z-index can clip it. createPortal renders the window into a different DOM node, but events and context still flow through the React tree, so a button in the window can call dispatch or read translations:
function AlertModal({ message, onClose }) {
return createPortal(
<div className="modal-overlay">
<div className="modal-content">
<h2>Alert!</h2>
<p>{message}</p>
<button onClick={onClose}>Close</button>
</div>
</div>,
document.getElementById('modal-root')
);
}You add the #modal-root node in index.html next to #root. In the editor below the portal simply goes into document.body.
Work Plan
The easiest way is to build the project in layers and check that it works after every step:
- Start with
MissionProviderand its reducer, and one panel that shows the status and the fuel. - Add
LanguageProviderand pass every label through the translation function. - Build
DashboardwithDashboard.HeaderandDashboard.Panel, and put anErrorBoundaryin every panel. - Add the alert in a portal that appears when the fuel drops below 20%.
- Finally, measure renders in React DevTools and add
React.memo,useMemoanduseCallbackwhere they really save work.
Evaluation Criteria
- All 6 patterns (Portals, i18n, useReducer, Compound Components, Error Boundaries, memoization) must be implemented
- The application should work without console errors
- Language switching should update all labels
- The alert should appear automatically when fuel is low
The editor below contains a working skeleton of the command center with all six patterns. Switch the language, launch the mission, burn the fuel below 20% and simulate a failure of the systems panel to see every pattern in action. Then extend the application with your own ideas, for example an action that completes the mission, fleet statistics computed in useMemo or a third language, and compare it with the structure described above.
Code for this lesson: App.jsx
import { Component, createContext, memo, useCallback, useContext, useMemo, useReducer, useState } from 'react';
import { createPortal } from 'react-dom';
import './App.css';
// === I18N: Context with translations ===
const translations = {
pl: {
title: 'Centrum Dowodzenia MisjΔ
',
status: 'Status misji',
systems: 'Systemy',
crew: 'ZaΕoga',
fuel: 'Paliwo',
launch: 'Rozpocznij misjΔ',
abort: 'Przerwij misjΔ',
burnFuel: '-10% paliwa',
ready: 'Gotowi do startu',
inProgress: 'Misja w toku',
lowFuel: 'Uwaga! Niski poziom paliwa!',
alertTitle: 'Alarm',
dismiss: 'Zamknij',
addMember: 'Dodaj czΕonka',
namePlaceholder: 'ImiΔ astronauty',
active: 'aktywnych',
on: 'WΕ.',
off: 'WYΕ.',
engine: 'Silnik',
shields: 'Tarcze',
comms: 'Komunikacja',
navigation: 'Nawigacja',
commander: 'DowΓ³dca',
navigator: 'Nawigator',
recruit: 'Rekrut',
crashed: 'Panel ulegΕ awarii',
reload: 'ZaΕaduj ponownie',
simulateCrash: 'Symuluj awariΔ panelu',
},
en: {
title: 'Mission Command Center',
status: 'Mission status',
systems: 'Systems',
crew: 'Crew',
fuel: 'Fuel',
launch: 'Launch mission',
abort: 'Abort mission',
burnFuel: '-10% fuel',
ready: 'Ready for launch',
inProgress: 'Mission in progress',
lowFuel: 'Warning! Low fuel level!',
alertTitle: 'Alert',
dismiss: 'Dismiss',
addMember: 'Add member',
namePlaceholder: 'Astronaut name',
active: 'active',
on: 'ON',
off: 'OFF',
engine: 'Engine',
shields: 'Shields',
comms: 'Communications',
navigation: 'Navigation',
commander: 'Commander',
navigator: 'Navigator',
recruit: 'Recruit',
crashed: 'The panel has crashed',
reload: 'Reload',
simulateCrash: 'Simulate a panel failure',
},
};
const FIRST_LANG = 'en';
const SECOND_LANG = 'pl';
const LanguageContext = createContext(null);
function LanguageProvider({ children }) {
const [lang, setLang] = useState(FIRST_LANG);
const t = useCallback(key => translations[lang][key] ?? key, [lang]);
const toggleLang = useCallback(() => setLang(l => (l === FIRST_LANG ? SECOND_LANG : FIRST_LANG)), []);
const value = useMemo(() => ({ lang, t, toggleLang }), [lang, t, toggleLang]);
return <LanguageContext.Provider value={value}>{children}</LanguageContext.Provider>;
}
function useLanguage() {
return useContext(LanguageContext);
}
// === MISSION STATE: useReducer ===
const initialMission = {
status: 'ready',
fuel: 100,
systems: [
{ id: 1, key: 'engine', active: true },
{ id: 2, key: 'shields', active: false },
{ id: 3, key: 'comms', active: true },
{ id: 4, key: 'navigation', active: true },
],
crew: [
{ id: 1, name: 'Ra', role: 'commander' },
{ id: 2, name: 'Astro', role: 'navigator' },
],
};
function missionReducer(state, action) {
switch (action.type) {
case 'LAUNCH_MISSION':
return { ...state, status: 'inProgress', fuel: Math.max(0, state.fuel - 15) };
case 'ABORT_MISSION':
return { ...state, status: 'ready' };
case 'UPDATE_FUEL':
return { ...state, fuel: Math.max(0, state.fuel + action.payload) };
case 'TOGGLE_SYSTEM':
return {
...state,
systems: state.systems.map(s => (s.id === action.payload ? { ...s, active: !s.active } : s)),
};
case 'ADD_CREW_MEMBER':
return { ...state, crew: [...state.crew, { ...action.payload, role: 'recruit' }] };
default:
return state;
}
}
const MissionContext = createContext(null);
function MissionProvider({ children }) {
const [state, dispatch] = useReducer(missionReducer, initialMission);
const value = useMemo(() => ({ state, dispatch }), [state]);
return <MissionContext.Provider value={value}>{children}</MissionContext.Provider>;
}
function useMission() {
return useContext(MissionContext);
}
// === ERROR BOUNDARY: one panel failing does not take down the rest ===
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<p>{this.props.message}</p>
<button onClick={() => this.setState({ hasError: false })}>{this.props.retryLabel}</button>
</div>
);
}
return this.props.children;
}
}
// === COMPOUND COMPONENT: Dashboard, Dashboard.Header, Dashboard.Panel ===
function Dashboard({ children }) {
return <div className="dashboard">{children}</div>;
}
Dashboard.Header = memo(function DashboardHeader() {
const { t, lang, toggleLang } = useLanguage();
const next = lang === FIRST_LANG ? SECOND_LANG : FIRST_LANG;
return (
<header className="dashboard-header">
<h1>{t('title')}</h1>
<button className="lang-btn" onClick={toggleLang}>{next.toUpperCase()}</button>
</header>
);
});
Dashboard.Panel = memo(function DashboardPanel({ title, children }) {
const { t } = useLanguage();
return (
<section className="dashboard-panel">
<h2>{title}</h2>
<ErrorBoundary message={t('crashed')} retryLabel={t('reload')}>
{children}
</ErrorBoundary>
</section>
);
});
// === MISSION STATUS ===
const MissionStatus = memo(function MissionStatus() {
const { state, dispatch } = useMission();
const { t } = useLanguage();
const handleLaunch = useCallback(() => dispatch({ type: 'LAUNCH_MISSION' }), [dispatch]);
const handleAbort = useCallback(() => dispatch({ type: 'ABORT_MISSION' }), [dispatch]);
const handleBurn = useCallback(() => dispatch({ type: 'UPDATE_FUEL', payload: -10 }), [dispatch]);
return (
<div>
<div className="status-indicator">
<span className={'status-dot status-' + state.status} />
<span>{t(state.status)}</span>
</div>
<div className="fuel-bar">
<span>{t('fuel')}: {state.fuel}%</span>
<div className="fuel-track">
<div className={'fuel-fill' + (state.fuel < 20 ? ' fuel-low' : '')} style={{ width: state.fuel + '%' }} />
</div>
</div>
<div className="status-actions">
{state.status === 'ready' && <button className="btn-launch" onClick={handleLaunch}>{t('launch')}</button>}
{state.status === 'inProgress' && (
<>
<button className="btn-abort" onClick={handleAbort}>{t('abort')}</button>
<button className="btn-fuel" onClick={handleBurn}>{t('burnFuel')}</button>
</>
)}
</div>
</div>
);
});
// A sensor that throws an error during rendering on demand (Error Boundary test)
function SensorArray({ broken }) {
if (broken) {
throw new Error('Systems sensor failure');
}
return null;
}
// === SYSTEMS LIST ===
const SystemsList = memo(function SystemsList() {
const { state, dispatch } = useMission();
const { t } = useLanguage();
const [broken, setBroken] = useState(false);
const handleToggle = useCallback(id => dispatch({ type: 'TOGGLE_SYSTEM', payload: id }), [dispatch]);
const activeCount = useMemo(() => state.systems.filter(s => s.active).length, [state.systems]);
return (
<div>
<SensorArray broken={broken} />
<p className="systems-count">{activeCount}/{state.systems.length} {t('active')}</p>
{state.systems.map(system => (
<div key={system.id} className="system-item">
<span>{t(system.key)}</span>
<button className={system.active ? 'sys-on' : 'sys-off'} onClick={() => handleToggle(system.id)}>
{system.active ? t('on') : t('off')}
</button>
</div>
))}
<button className="btn-crash" onClick={() => setBroken(true)}>{t('simulateCrash')}</button>
</div>
);
});
// === CREW LIST ===
const CrewList = memo(function CrewList() {
const { state, dispatch } = useMission();
const { t } = useLanguage();
const [name, setName] = useState('');
const handleAdd = useCallback(() => {
if (!name.trim()) return;
// The id is created in the handler, because the reducer must stay a pure function
dispatch({ type: 'ADD_CREW_MEMBER', payload: { id: Date.now(), name: name.trim() } });
setName('');
}, [name, dispatch]);
return (
<div>
{state.crew.map(member => (
<div key={member.id} className="crew-item">
<strong>{member.name}</strong>
<span>{t(member.role)}</span>
</div>
))}
<div className="crew-add">
<input
value={name}
onChange={e => setName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleAdd()}
placeholder={t('namePlaceholder')}
/>
<button onClick={handleAdd}>{t('addMember')}</button>
</div>
</div>
);
});
// === ALERT IN A PORTAL: rendered outside the dashboard tree ===
function AlertModal({ onDismiss }) {
const { t } = useLanguage();
return createPortal(
<div className="modal-overlay">
<div className="modal-content">
<h2>{t('alertTitle')}</h2>
<p>{t('lowFuel')}</p>
<button onClick={onDismiss}>{t('dismiss')}</button>
</div>
</div>,
document.body
);
}
// === MAIN APPLICATION ===
function MissionControl() {
const { state } = useMission();
const { t } = useLanguage();
const [dismissedAt, setDismissedAt] = useState(null);
// The alert is derived from state: low fuel during the mission, unless it was dismissed at this level
const showAlert = state.status === 'inProgress' && state.fuel < 20 && dismissedAt !== state.fuel;
return (
<>
<Dashboard>
<Dashboard.Header />
<div className="panels-grid">
<Dashboard.Panel title={t('status')}>
<MissionStatus />
</Dashboard.Panel>
<Dashboard.Panel title={t('systems')}>
<SystemsList />
</Dashboard.Panel>
<Dashboard.Panel title={t('crew')}>
<CrewList />
</Dashboard.Panel>
</div>
</Dashboard>
{showAlert && <AlertModal onDismiss={() => setDismissedAt(state.fuel)} />}
</>
);
}
export default function App() {
return (
<LanguageProvider>
<MissionProvider>
<MissionControl />
</MissionProvider>
</LanguageProvider>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?