JavaScript and React course ยท Module 4: Context API and useReducer

Project: Galactic Command Center

4 min read ยท
In this lesson5

Throughout this module you've been building knowledge step by step: Context API, reducers, combining these tools, optimization. Now it's time to bring it all together in one project - the Galactic Command Center.

This is not another theoretical lesson. This is a project that you'll build yourself, using everything you've learned.

What will you build?

An application managing a fleet of spaceships with three independent systems, each with its own context:

  • ThemeContext - a theme toggle (daytime mode "Sunrise" / nighttime mode "Deep Space")
  • AuthContext - an authorization system (Captain logged in / logged out)
  • MissionContext - the heart of the application: mission management via useReducer

Components on screen will consume different contexts depending on their needs.

Project requirements

1. ThemeContext

The context stores the current theme and a toggle function. The ThemeToggle component changes the theme, and the rest of the application reacts to the change (e.g., a CSS class on the main container).

// Expected context structure
{
  theme: 'dark' | 'light',
  toggleTheme: () => void
}

2. AuthContext

The context stores captain data and enables login/logout. The login form should accept the captain's name. After logging in, display a greeting and a logout button.

// Expected context structure
{
  captain: { name: string } | null,
  login: (name: string) => void,
  logout: () => void
}

3. MissionContext with useReducer

This is the main part of the project. The reducer handles at least 4 action types:

// Action types to implement
'ADD_MISSION'      // adds a new mission to the list
'UPDATE_STATUS'    // changes the status of an existing mission
'ASSIGN_SHIP'      // assigns a ship to a mission
'COMPLETE_MISSION' // marks a mission as completed

// Example state shape
{
  missions: [
    {
      id: 1,
      name: 'Mars Exploration',
      status: 'planning' | 'active' | 'completed',
      assignedShip: string | null
    }
  ],
  availableShips: ['USS Nova', 'Orion-7', 'Celestia']
}

Component structure

The application should consist of the following components:

function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <MissionProvider>
          <div className="app">
            <Header />        {/* uses AuthContext + ThemeContext */}
            <MissionDashboard /> {/* uses MissionContext + AuthContext */}
            <ThemeToggle />   {/* uses ThemeContext */}
          </div>
        </MissionProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

Header - displays the application title, login status (from AuthContext), and the current theme.

MissionDashboard - mission list, form for adding a new mission, assigning ships. Accessible only to logged-in captains.

ThemeToggle - a button that toggles between daytime and nighttime modes.

Implementation tips

Start by building each provider separately and testing it before combining them all. A good order is: ThemeProvider (simplest) -> AuthProvider -> MissionProvider.

Remember custom hooks for each context:

function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error('useTheme must be inside ThemeProvider');
  return ctx;
}

function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be inside AuthProvider');
  return ctx;
}

function useMissions() {
  const ctx = useContext(MissionContext);
  if (!ctx) throw new Error('useMissions must be inside MissionProvider');
  return ctx;
}

For MissionContext, apply the pattern of splitting into a state context and a dispatch context that you learned in the previous lesson - this is good practice with complex state using useReducer.

What to demonstrate in the project

The completed project should show:

  1. Three independent context systems working simultaneously
  2. The Header component consuming both AuthContext and ThemeContext
  3. Theme changes immediately visible throughout the entire application
  4. Adding missions and changing their status through dispatch
  5. Blocking the mission panel for unauthenticated users
  6. Assigning a ship to a mission (ASSIGN_SHIP action with payload)

The project is intentionally described broadly - this is your chance to take a creative approach to the solution. Use the editor below to build your version of the Galactic Command Center.

Code for this lesson: App.jsx
import React, { createContext, useContext, useReducer, useState } from 'react';

// ============================================================
// PROJECT: Galactic Command Center
// Task: Complete the missing code fragments (marked with TODO)
// ============================================================

// --- 1. THEME CONTEXT ---
const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [darkMode, setDarkMode] = useState(true);
  // TODO: Also add the toggleTheme function to value
  return (
    <ThemeContext.Provider value={{ darkMode, toggleTheme: () => setDarkMode(d => !d) }}>
      {children}
    </ThemeContext.Provider>
  );
}

function useTheme() {
  // TODO: Use useContext to read ThemeContext
  return useContext(ThemeContext);
}

// --- 2. AUTH CONTEXT ---
const AuthContext = createContext();

const authInitialState = { user: null, isLoggedIn: false };

function authReducer(state, action) {
  switch (action.type) {
    case 'LOGIN':
      // TODO: Return new state with user: action.user and isLoggedIn: true
      return { ...state, user: action.user, isLoggedIn: true };
    case 'LOGOUT':
      return authInitialState;
    default:
      return state;
  }
}

function AuthProvider({ children }) {
  const [state, dispatch] = useReducer(authReducer, authInitialState);
  return (
    <AuthContext.Provider value={{ ...state, dispatch }}>
      {children}
    </AuthContext.Provider>
  );
}

function useAuth() { return useContext(AuthContext); }

// --- 3. MISSION CONTEXT ---
const MissionContext = createContext();

const missionInitialState = { missions: [] };

function missionReducer(state, action) {
  switch (action.type) {
    case 'ADD_MISSION':
      // TODO: Add new mission to the missions array
      // Mission has fields: id, name, status: 'pending', createdBy
      return {
        ...state,
        missions: [
          ...state.missions,
          { id: Date.now(), name: action.name, status: 'pending', createdBy: action.createdBy },
        ],
      };
    case 'UPDATE_STATUS':
      return {
        ...state,
        missions: state.missions.map(m =>
          m.id === action.id ? { ...m, status: action.status } : m
        ),
      };
    default:
      return state;
  }
}

function MissionProvider({ children }) {
  const [state, dispatch] = useReducer(missionReducer, missionInitialState);
  // TODO: Wrap children in MissionContext.Provider with value={{ ...state, dispatch }}
  return (
    <MissionContext.Provider value={{ ...state, dispatch }}>
      {children}
    </MissionContext.Provider>
  );
}

function useMission() { return useContext(MissionContext); }

// --- UI COMPONENTS ---

function LoginPanel() {
  const { isLoggedIn, user, dispatch } = useAuth();
  const [name, setName] = useState('');
  if (isLoggedIn) {
    return (
      <div style={panel}>
        <span style={{ color: '#4fc3f7' }}>Logged in: <b>{user}</b></span>
        <button onClick={() => dispatch({ type: 'LOGOUT' })} style={{ ...btn, marginLeft: 12 }}>
          Log out
        </button>
      </div>
    );
  }
  return (
    <div style={panel}>
      <input
        value={name} onChange={e => setName(e.target.value)}
        placeholder="Your name (pilot)..." style={input}
      />
      <button
        onClick={() => { if (name.trim()) dispatch({ type: 'LOGIN', user: name.trim() }); }}
        style={{ ...btn, background: '#4fc3f7', color: '#0a0e1a' }}
      >
        Log in
      </button>
    </div>
  );
}

function MissionPanel() {
  const { isLoggedIn, user } = useAuth();
  const { missions, dispatch } = useMission();
  const [newMission, setNewMission] = useState('');
  const statusLabels = { pending: 'โณ Pending', active: 'Active', done: 'Completed' };
  const statusColors = { pending: '#ff9800', active: '#4fc3f7', done: '#4caf50' };

  if (!isLoggedIn) {
    return (
      <div style={{ ...panel, color: '#778da9', textAlign: 'center' }}>
        Log in to manage missions
      </div>
    );
  }

  return (
    <div style={panel}>
      <h3 style={{ color: '#4fc3f7', marginTop: 0 }}>Space missions</h3>
      <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
        <input
          value={newMission} onChange={e => setNewMission(e.target.value)}
          placeholder="Mission name..." style={{ ...input, flex: 1 }}
        />
        <button
          onClick={() => {
            // TODO: Call dispatch with type: 'ADD_MISSION', name: newMission, createdBy: user
            if (newMission.trim()) {
              dispatch({ type: 'ADD_MISSION', name: newMission.trim(), createdBy: user });
              setNewMission('');
            }
          }}
          style={{ ...btn, background: '#4fc3f7', color: '#0a0e1a' }}
        >
          Add
        </button>
      </div>
      {missions.length === 0 && (
        <p style={{ color: '#555', textAlign: 'center' }}>No missions. Add the first one!</p>
      )}
      {missions.map(m => (
        <div key={m.id} style={{ ...missionRow }}>
          <div>
            <div style={{ fontWeight: 'bold' }}>{m.name}</div>
            <div style={{ fontSize: 11, color: '#778da9' }}>Pilot: {m.createdBy}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ color: statusColors[m.status], fontSize: 12 }}>
              {statusLabels[m.status]}
            </span>
            {m.status === 'pending' && (
              <button onClick={() => dispatch({ type: 'UPDATE_STATUS', id: m.id, status: 'active' })} style={btn}>
                Activate
              </button>
            )}
            {m.status === 'active' && (
              <button onClick={() => dispatch({ type: 'UPDATE_STATUS', id: m.id, status: 'done' })} style={btn}>
                Complete
              </button>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

function ThemeToggle() {
  const { darkMode, toggleTheme } = useTheme();
  return (
    <button onClick={toggleTheme} style={{ ...btn, float: 'right', marginBottom: 12 }}>
      {darkMode ? 'Light theme' : 'Dark theme'}
    </button>
  );
}

// --- MAIN APPLICATION ---
// TODO: Wrap App in ThemeProvider, AuthProvider and MissionProvider (order matters!)
function App() {
  const { darkMode } = useTheme();
  const bg = darkMode ? '#0a0e1a' : '#e8f4fd';
  const fg = darkMode ? 'white' : '#0a0e1a';

  return (
    <div style={{ minHeight: '100vh', background: bg, padding: 24, fontFamily: 'Arial', color: fg, transition: 'all 0.3s' }}>
      <ThemeToggle />
      <h1 style={{ textAlign: 'center', color: '#ffd700', marginBottom: 24, clear: 'both' }}>
        Galactic Command Center
      </h1>
      <LoginPanel />
      <MissionPanel />
    </div>
  );
}

function WrappedApp() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <MissionProvider>
          <App />
        </MissionProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

// Style
const panel = {
  background: '#1a2035', borderRadius: 10, padding: 16, marginBottom: 14,
  border: '1px solid rgba(79,195,247,0.2)',
};
const btn = {
  background: 'rgba(255,255,255,0.08)', color: 'white',
  border: '1px solid rgba(255,255,255,0.2)', borderRadius: 6,
  padding: '5px 12px', cursor: 'pointer', fontSize: 12,
};
const input = {
  background: '#0a0e1a', color: 'white',
  border: '1px solid rgba(79,195,247,0.3)', borderRadius: 6,
  padding: '6px 10px', boxSizing: 'border-box',
};
const missionRow = {
  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
  padding: '8px 0', borderBottom: '1px solid rgba(255,255,255,0.07)',
};

export { WrappedApp as default };

Docs entries used in this lesson

Spotted a mistake in this lesson?

  1. Project to submitMentor Project: Galactic Command Center
  2. VideoVideo: Module Summary

Useful articles