JavaScript and React course Β· Module 9: Modern React Hooks

Project: Advanced React 18+ Application

13 min read Β·
In this lesson4

Every crew eventually goes through a full mission simulation, with all systems running at once. You already know transitions, deferred values, useId, use and useOptimistic, but separately. Now they have to cooperate in one codebase.

In this project, you will create a modern React application using all the React 18+ features you have learned. You will build an Advanced Task Management System - an advanced task management system utilizing Concurrent Features, Server Components, and modern hooks.

Project Specification

Main Features

  1. Dashboard with real-time updates

    • Using useTransition and useDeferredValue
    • Optimistic updates with useOptimistic
    • Content streaming with Suspense
  2. Advanced forms

    • useFormStatus and useActionState
    • Server Actions
    • Real-time validation
  3. Notification system

    • useId for accessibility
    • Concurrent rendering
    • Progressive enhancement
  4. Performance and optimization

    • React Compiler (optional)
    • Automatic Batching
    • Selective Hydration

React Compiler has had a stable 1.0 release since 2025 and adds memoization by itself, so it is worth considering.

Application Structure

The project uses the Next.js App Router, a framework that supports Server Components and Server Actions. Here is the directory map:

src/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ layout.tsx          # Root layout (Server Component)
β”‚   β”œβ”€β”€ page.tsx            # Home page
β”‚   β”œβ”€β”€ dashboard/
β”‚   β”‚   β”œβ”€β”€ page.tsx        # Dashboard (Server Component)
β”‚   β”‚   └── loading.tsx     # Loading UI
β”‚   β”œβ”€β”€ tasks/
β”‚   β”‚   β”œβ”€β”€ page.tsx        # Tasks list
β”‚   β”‚   β”œβ”€β”€ [id]/page.tsx   # Task details
β”‚   β”‚   └── new/page.tsx    # Create task
β”‚   └── api/
β”‚       β”œβ”€β”€ tasks/route.ts  # Tasks API
β”‚       └── notifications/route.ts
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ ui/                 # Basic UI components
β”‚   β”œβ”€β”€ forms/              # Form components
β”‚   β”œβ”€β”€ dashboard/          # Dashboard components
β”‚   └── tasks/              # Task components
β”œβ”€β”€ hooks/                  # Custom hooks
β”œβ”€β”€ lib/                    # Utilities
└── types/                  # TypeScript types

The app/ folder holds the routes, components/ the UI building blocks, and lib/ the server logic.

Step-by-step Implementation

Step 1: Basic structure and types

We start with the data. A TypeScript interface is a contract describing the fields of a task, a user and a notification:

// types/index.ts
export interface Task {
  id: string;
  title: string;
  description: string;
  status: 'pending' | 'in_progress' | 'completed';
  priority: 'low' | 'medium' | 'high';
  assignee?: string;
  dueDate?: Date;
  createdAt: Date;
  updatedAt: Date;
}

export interface User {
  id: string;
  name: string;
  email: string;
  avatar?: string;
}

export interface Notification {
  id: string;
  type: 'task_created' | 'task_updated' | 'task_completed';
  message: string;
  timestamp: Date;
  read: boolean;
}

Fields with a question mark, such as assignee?, are optional, and unions like 'low' | 'medium' | 'high' allow only the listed values.

Step 2: Root Layout with Server Components

The layout is an async Server Component, so it can fetch the user's data while still on the server:

// app/layout.tsx (Server Component)
import { Suspense } from 'react';
import { Navigation } from '@/components/Navigation';
import { NotificationProvider } from '@/components/NotificationProvider';

async function RootLayout({ children }: { children: React.ReactNode }) {
  // Fetch user data on the server
  const user = await getCurrentUser();
  const notifications = await getUnreadNotifications(user.id);

  return (
    <html lang="en">
      <head>
        <title>Advanced Task Manager</title>
        <meta name="description" content="Advanced task management system" />
      </head>
      <body>
        <NotificationProvider initialNotifications={notifications}>
          <div className="app-layout">
            <Suspense fallback={<NavigationSkeleton />}>
              <Navigation user={user} />
            </Suspense>

            <main className="main-content">
              <Suspense fallback={<PageSkeleton />}>
                {children}
              </Suspense>
            </main>
          </div>
        </NotificationProvider>
      </body>
    </html>
  );
}

export default RootLayout;

Two Suspense boundaries let the navigation and the content appear independently. In Next.js, the page title and description are usually defined through a metadata export rather than a hand-written <head>.

Step 3: Dashboard with Concurrent Features

The dashboard page fetches statistics and recent tasks in parallel and streams the slower sections:

// app/dashboard/page.tsx (Server Component)
import { Suspense } from 'react';
import { TasksOverview } from '@/components/dashboard/TasksOverview';
import { RecentActivity } from '@/components/dashboard/RecentActivity';
import { PerformanceMetrics } from '@/components/dashboard/PerformanceMetrics';

async function DashboardPage() {
  // Parallel data fetching
  const [tasksStats, recentTasks] = await Promise.all([
    getTasksStatistics(),
    getRecentTasks(10)
  ]);

  return (
    <div className="dashboard">
      <h1>Dashboard</h1>

      {/* Fast-loading section */}
      <TasksOverview stats={tasksStats} />

      <div className="dashboard-grid">
        {/* Streams independently */}
        <Suspense fallback={<RecentActivitySkeleton />}>
          <RecentActivity initialTasks={recentTasks} />
        </Suspense>

        {/* Can load later */}
        <Suspense fallback={<MetricsSkeleton />}>
          <PerformanceMetrics />
        </Suspense>
      </div>
    </div>
  );
}

export default DashboardPage;

TasksOverview appears immediately, while PerformanceMetrics loads later.

Step 4: Interactive Components with new hooks

The 'use client' directive marks the boundary beyond which code is sent to the browser and can use state:

// components/dashboard/RecentActivity.tsx (Client Component)
'use client';

import { useState, useTransition, useDeferredValue } from 'react';
import { Task } from '@/types';

interface RecentActivityProps {
  initialTasks: Task[];
}

export function RecentActivity({ initialTasks }: RecentActivityProps) {
  const [tasks, setTasks] = useState(initialTasks);
  const [searchQuery, setSearchQuery] = useState('');
  const [isPending, startTransition] = useTransition();

  // Deferred value for search
  const deferredSearchQuery = useDeferredValue(searchQuery);

  // Filter tasks using deferredValue
  const filteredTasks = tasks.filter(task =>
    task.title.toLowerCase().includes(deferredSearchQuery.toLowerCase()) ||
    task.description.toLowerCase().includes(deferredSearchQuery.toLowerCase())
  );

  const handleSearch = (query: string) => {
    setSearchQuery(query);

    // Use transition for less priority updates
    startTransition(() => {
      // Additional operations that can be interrupted
      updateSearchAnalytics(query);
    });
  };

  const refreshTasks = async () => {
    startTransition(async () => {
      const newTasks = await fetchRecentTasks();
      setTasks(newTasks);
    });
  };

  return (
    <div className="recent-activity">
      <div className="activity-header">
        <h2>Recent Activity</h2>
        <button
          onClick={refreshTasks}
          disabled={isPending}
          className={isPending ? 'loading' : ''}
        >
          {isPending ? 'Refreshing...' : 'Refresh'}
        </button>
      </div>

      <SearchInput
        value={searchQuery}
        onChange={handleSearch}
        isPending={isPending}
      />

      <div className="tasks-list">
        {filteredTasks.map(task => (
          <TaskCard
            key={task.id}
            task={task}
            onUpdate={setTasks}
          />
        ))}

        {deferredSearchQuery && filteredTasks.length === 0 && (
          <div className="no-results">
            No results for "{deferredSearchQuery}"
          </div>
        )}
      </div>
    </div>
  );
}

The list filters by deferredSearchQuery, so the search field does not slow down. Two notes: startTransition in handleSearch does not interrupt the updateSearchAnalytics call itself, because only renders caused by state changes can be interrupted. And setTasks after await should, according to react.dev, go into another startTransition.

Step 5: Advanced forms with Server Actions

The form combines three hooks. useActionState holds the action's result, useOptimistic shows the save immediately, and useFormStatus tells the button about the submission. Important: useFormStatus is imported from react-dom, not from react. First, the logic:

// components/forms/TaskForm.tsx (Client Component)
'use client';

import { useActionState, useEffect, useId, useOptimistic } from 'react';
import { useFormStatus } from 'react-dom';
import { Task } from '@/types';
import { createTask, updateTask } from '@/lib/actions';

interface TaskFormProps {
  task?: Task;
  onSuccess?: () => void;
}

export function TaskForm({ task, onSuccess }: TaskFormProps) {
  const formId = useId();
  const titleId = useId();
  const descriptionId = useId();

  // useActionState for action state management
  const [state, formAction] = useActionState(
    task ? updateTask.bind(null, task.id) : createTask,
    {
      success: false,
      errors: {},
      data: task || null
    }
  );

  // useOptimistic for instant feedback
  const [optimisticState, addOptimistic] = useOptimistic(
    state,
    (currentState, optimisticUpdate) => ({
      ...currentState,
      ...optimisticUpdate,
      optimistic: true
    })
  );

  const handleSubmit = async (formData: FormData) => {
    // Optimistic update
    addOptimistic({
      success: true,
      data: {
        id: task?.id || 'temp-' + Date.now(),
        title: formData.get('title') as string,
        description: formData.get('description') as string,
        status: formData.get('status') as Task['status'],
        priority: formData.get('priority') as Task['priority'],
        createdAt: new Date(),
        updatedAt: new Date()
      }
    });

    // Execute actual action
    formAction(formData);
  };

  // The new state arrives in the next render, so we react to it in an effect
  useEffect(() => {
    if (state.success) {
      onSuccess?.();
    }
  }, [state, onSuccess]);

The formAction function does not return a Promise, and state in this closure is still the old state. That is why we react to success in an effect, once the new state arrives in the next render. Now the form view:

  return (
    <form
      id={formId}
      action={handleSubmit}
      className="task-form"
    >
      <div className="form-group">
        <label htmlFor={titleId}>Task title</label>
        <input
          id={titleId}
          name="title"
          type="text"
          required
          defaultValue={optimisticState.data?.title || ''}
          className={optimisticState.errors?.title ? 'error' : ''}
        />
        {optimisticState.errors?.title && (
          <span className="error-message" role="alert">
            {optimisticState.errors.title}
          </span>
        )}
      </div>

      <div className="form-group">
        <label htmlFor={descriptionId}>Description</label>
        <textarea
          id={descriptionId}
          name="description"
          rows={4}
          defaultValue={optimisticState.data?.description || ''}
        />
      </div>

      <div className="form-group">
        <label>Status</label>
        <select name="status" defaultValue={optimisticState.data?.status || 'pending'}>
          <option value="pending">Pending</option>
          <option value="in_progress">In Progress</option>
          <option value="completed">Completed</option>
        </select>
      </div>

      <div className="form-group">
        <label>Priority</label>
        <select name="priority" defaultValue={optimisticState.data?.priority || 'medium'}>
          <option value="low">Low</option>
          <option value="medium">Medium</option>
          <option value="high">High</option>
        </select>
      </div>

      <FormSubmitButton />

      {optimisticState.optimistic && (
        <div className="optimistic-indicator">
          Saving...
        </div>
      )}

      {optimisticState.success && !optimisticState.optimistic && (
        <div className="success-message">
          Task has been {task ? 'updated' : 'created'}!
        </div>
      )}
    </form>
  );
}

// Component using useFormStatus
function FormSubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button
      type="submit"
      disabled={pending}
      className={pending ? 'loading' : ''}
    >
      {pending ? 'Saving...' : 'Save task'}
    </button>
  );
}

FormSubmitButton is a separate component because useFormStatus reads the status of the parent form, so it must be called inside a <form>.

Step 6: Server Actions

The 'use server' directive makes these functions run only on the server. We validate with the Zod library:

// lib/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';

const TaskSchema = z.object({
  title: z.string().min(1, 'Title is required').max(100, 'Title is too long'),
  description: z.string().optional(),
  status: z.enum(['pending', 'in_progress', 'completed']),
  priority: z.enum(['low', 'medium', 'high']),
  dueDate: z.string().optional().transform(str => str ? new Date(str) : undefined)
});

export async function createTask(prevState: any, formData: FormData) {
  try {
    const validatedFields = TaskSchema.safeParse({
      title: formData.get('title'),
      description: formData.get('description'),
      status: formData.get('status'),
      priority: formData.get('priority'),
      dueDate: formData.get('dueDate')
    });

    if (!validatedFields.success) {
      return {
        success: false,
        errors: z.flattenError(validatedFields.error).fieldErrors,
        data: null
      };
    }

    const task = await db.tasks.create({
      data: {
        ...validatedFields.data,
        id: generateId(),
        createdAt: new Date(),
        updatedAt: new Date()
      }
    });

    // Revalidate cache
    revalidatePath('/dashboard');
    revalidatePath('/tasks');

    return {
      success: true,
      errors: {},
      data: task
    };

  } catch (error) {
    return {
      success: false,
      errors: { _form: ['An error occurred while creating the task'] },
      data: null
    };
  }
}

safeParse does not throw, it returns an object with a success field. We flatten errors with z.flattenError, because in Zod 4 the error.flatten() method is marked as deprecated. The update action looks similar:

export async function updateTask(taskId: string, prevState: any, formData: FormData) {
  try {
    const validatedFields = TaskSchema.safeParse({
      title: formData.get('title'),
      description: formData.get('description'),
      status: formData.get('status'),
      priority: formData.get('priority'),
      dueDate: formData.get('dueDate')
    });

    if (!validatedFields.success) {
      return {
        success: false,
        errors: z.flattenError(validatedFields.error).fieldErrors,
        data: null
      };
    }

    const task = await db.tasks.update({
      where: { id: taskId },
      data: {
        ...validatedFields.data,
        updatedAt: new Date()
      }
    });

    revalidatePath(`/tasks/${taskId}`);
    revalidatePath('/dashboard');

    return {
      success: true,
      errors: {},
      data: task
    };

  } catch (error) {
    return {
      success: false,
      errors: { _form: ['An error occurred while updating the task'] },
      data: null
    };
  }
}

updateTask receives taskId as its first argument thanks to bind in the form, and revalidatePath refreshes the pages' data.

Step 7: Advanced Suspense Patterns

Suspense boundaries can be nested, all the way down to a single card:

// components/tasks/TasksList.tsx (Server Component)
import { Suspense } from 'react';
import { TaskCard } from './TaskCard';
import { TasksFilter } from './TasksFilter';

async function TasksList({ searchParams }: { searchParams: any }) {
  return (
    <div className="tasks-page">
      <div className="tasks-header">
        <h1>Tasks</h1>

        {/* Filter doesn't require Suspense - loads quickly */}
        <TasksFilter />
      </div>

      <div className="tasks-content">
        {/* Main task list */}
        <Suspense fallback={<TasksListSkeleton />}>
          <TasksGrid searchParams={searchParams} />
        </Suspense>

        {/* Sidebar with additional info */}
        <aside className="tasks-sidebar">
          <Suspense fallback={<StatsSkeleton />}>
            <TasksStatistics />
          </Suspense>

          <Suspense fallback={<ActivitySkeleton />}>
            <RecentActivity />
          </Suspense>
        </aside>
      </div>
    </div>
  );
}

// Component with long load time
async function TasksGrid({ searchParams }: { searchParams: any }) {
  // Simulate a long query
  const tasks = await getFilteredTasks(searchParams);

  return (
    <div className="tasks-grid">
      {tasks.map(task => (
        <Suspense
          key={task.id}
          fallback={<TaskCardSkeleton />}
        >
          <TaskCard task={task} />
        </Suspense>
      ))}
    </div>
  );
}

Since Next.js 15, searchParams on a page is a Promise, so you have to read it with await before using it.

Step 8: Accessibility with useId

A universal form field injects identifiers into its child:

// components/ui/FormField.tsx
'use client';

import { useId, forwardRef, cloneElement } from 'react';

interface FormFieldProps {
  label: string;
  error?: string;
  help?: string;
  required?: boolean;
  children: React.ReactNode;
}

export const FormField = forwardRef<HTMLDivElement, FormFieldProps>(
  ({ label, error, help, required, children }, ref) => {
    const fieldId = useId();
    const errorId = useId();
    const helpId = useId();

    return (
      <div ref={ref} className="form-field">
        <label
          htmlFor={fieldId}
          className={required ? 'required' : ''}
        >
          {label}
          {required && <span aria-hidden="true">*</span>}
        </label>

        <div className="field-input">
          {cloneElement(children as React.ReactElement, {
            id: fieldId,
            'aria-describedby': [
              help ? helpId : null,
              error ? errorId : null
            ].filter(Boolean).join(' ') || undefined,
            'aria-invalid': error ? 'true' : undefined,
            required
          })}
        </div>

        {help && (
          <div id={helpId} className="field-help">
            {help}
          </div>
        )}

        {error && (
          <div
            id={errorId}
            className="field-error"
            role="alert"
            aria-live="polite"
          >
            {error}
          </div>
        )}
      </div>
    );
  }
);

FormField.displayName = 'FormField';

In React 19, ref is a regular prop of a function component, and forwardRef is planned to be deprecated in the future, so in new code you can accept ref directly.

Step 9: Performance Monitoring

Finally, a context that collects performance metrics:

// components/providers/PerformanceProvider.tsx
'use client';

import { createContext, useContext, useEffect, useState } from 'react';

interface PerformanceMetrics {
  renderTime: number;
  interactionTime: number;
  suspenseTime: number;
}

const PerformanceContext = createContext<{
  metrics: PerformanceMetrics;
  recordMetric: (type: keyof PerformanceMetrics, time: number) => void;
}>({
  metrics: { renderTime: 0, interactionTime: 0, suspenseTime: 0 },
  recordMetric: () => {}
});

export function PerformanceProvider({ children }: { children: React.ReactNode }) {
  const [metrics, setMetrics] = useState<PerformanceMetrics>({
    renderTime: 0,
    interactionTime: 0,
    suspenseTime: 0
  });

  const recordMetric = (type: keyof PerformanceMetrics, time: number) => {
    setMetrics(prev => ({
      ...prev,
      [type]: time
    }));

    // Send metrics to analytics system
    if (time > getThreshold(type)) {
      analytics.track('performance_issue', {
        type,
        time,
        url: window.location.pathname
      });
    }
  };

  useEffect(() => {
    // Observe Web Vitals
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.entryType === 'measure') {
          recordMetric('renderTime', entry.duration);
        }
      }
    });

    observer.observe({ entryTypes: ['measure'] });

    return () => observer.disconnect();
  }, []);

  return (
    <PerformanceContext.Provider value={{ metrics, recordMetric }}>
      {children}
    </PerformanceContext.Provider>
  );
}

export const usePerformance = () => useContext(PerformanceContext);

function getThreshold(type: keyof PerformanceMetrics): number {
  const thresholds = {
    renderTime: 100,      // 100ms
    interactionTime: 50,  // 50ms
    suspenseTime: 1000    // 1s
  };
  return thresholds[type];
}

PerformanceObserver listens here for measure entries, meaning your own measurements, not Web Vitals. For Core Web Vitals use the web-vitals library.

Project Summary

This project demonstrates:

  1. Concurrent Features: useTransition, useDeferredValue for responsive UI
  2. Form Handling: useActionState, useFormStatus with Server Actions
  3. Accessibility: useId for unique identifiers
  4. Optimistic Updates: useOptimistic for instant feedback
  5. Server Components: Server-side rendering with parallel data fetching
  6. Suspense Patterns: Hierarchical loading with streaming
  7. Performance: Monitoring and performance optimization
  8. Error Handling: Granular Error Boundaries
  9. Type Safety: Full TypeScript utilization

Next steps for extension:

  1. Add real-time synchronization with WebSockets
  2. Implement offline support with Service Workers
  3. Add advanced filters and sorting
  4. Create a user permissions system
  5. Integrate with push notification system
  6. Add data export to various formats
  7. Implement dark mode with CSS-in-JS
  8. Create a mobile app with React Native

This project is a solid foundation for building modern React applications utilizing the latest framework features.

My advice: build step by step and run the application after every step. Remember: a good mission is one where every system on the ship knows its job, and mission control sees all of them at once.

Code for this lesson: App.jsx
import React, {
  useState, useMemo, useCallback, memo,
  useTransition, useDeferredValue, Suspense, lazy, createContext, use,
} from 'react';

// ========================
// APPLICATION CONTEXTS
// ========================
const ThemeContext = createContext('dark');

// ========================
// SIMULATED DATA
// ========================
function generateCrewMembers(count) {
  const roles = ['Pilot', 'Navigator', 'Engineer', 'Medic', 'Scientist', 'Technician'];
  const statuses = ['Active', 'On mission', 'Resting', 'Training'];
  const members = [];
  for (let i = 0; i < count; i++) {
    members.push({
      id: i + 1,
      name: `Astronaut-${(i + 1).toString().padStart(3, '0')}`,
      role: roles[i % roles.length],
      status: statuses[i % statuses.length],
      missions: Math.floor(Math.random() * 50),
      rating: (3 + Math.random() * 2).toFixed(1),
    });
  }
  return members;
}

const ALL_CREW = generateCrewMembers(200);

// ========================
// OPTIMIZED COMPONENTS
// ========================

// React.memo - prevents unnecessary re-renders
const StatCard = memo(function StatCard({ label, value, color, icon }) {
  return (
    <div style={{
      padding: '16px', borderRadius: '10px',
      background: `${color}11`, border: `1px solid ${color}33`,
      textAlign: 'center', minWidth: '120px',
    }}>
      <div style={{ fontSize: '24px', marginBottom: '4px' }}>{icon}</div>
      <div style={{ fontSize: '22px', fontWeight: 'bold', color }}>{value}</div>
      <div style={{ fontSize: '12px', color: '#778da9', marginTop: '4px' }}>{label}</div>
    </div>
  );
});

// Memoized table row
const CrewRow = memo(function CrewRow({ member, onSelect }) {
  const statusColor = {
    'Active': '#4ecdc4',
    'On mission': '#ffd700',
    'Resting': '#778da9',
    'Training': '#00d4ff',
  }[member.status] || '#778da9';

  return (
    <div
      onClick={() => onSelect(member)}
      style={{
        display: 'grid', gridTemplateColumns: '1fr 100px 90px 60px 50px',
        padding: '10px 14px', fontSize: '13px',
        borderBottom: '1px solid #1a2a3c', cursor: 'pointer',
        transition: 'background 0.15s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,212,255,0.05)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <span style={{ color: '#e0e1dd' }}>{member.name}</span>
      <span style={{ color: '#778da9' }}>{member.role}</span>
      <span style={{ color: statusColor }}>{member.status}</span>
      <span style={{ color: '#c0c8d0', textAlign: 'center' }}>{member.missions}</span>
      <span style={{ color: '#ffd700', textAlign: 'center' }}>{member.rating}</span>
    </div>
  );
});

// TODO 1: Wrap DetailPanel component in React.memo
// It should render only when selectedMember changes
function DetailPanel({ selectedMember }) {
  if (!selectedMember) {
    return (
      <div style={{
        padding: '40px', textAlign: 'center', color: '#556677',
        background: 'rgba(255,255,255,0.02)', borderRadius: '10px',
      }}>
        Select a crew member to see details
      </div>
    );
  }
  return (
    <div style={{
      padding: '20px', background: 'rgba(0, 212, 255, 0.04)',
      borderRadius: '10px', border: '1px solid #1a3a5c',
    }}>
      <h3 style={{ color: '#00d4ff', margin: '0 0 12px' }}>{selectedMember.name}</h3>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', fontSize: '13px' }}>
        <div><span style={{ color: '#778da9' }}>Role:</span> <span style={{ color: '#e0e1dd' }}>{selectedMember.role}</span></div>
        <div><span style={{ color: '#778da9' }}>Status:</span> <span style={{ color: '#4ecdc4' }}>{selectedMember.status}</span></div>
        <div><span style={{ color: '#778da9' }}>Missions:</span> <span style={{ color: '#e0e1dd' }}>{selectedMember.missions}</span></div>
        <div><span style={{ color: '#778da9' }}>Rating:</span> <span style={{ color: '#ffd700' }}>{selectedMember.rating}/5.0</span></div>
      </div>
    </div>
  );
}

// ========================
// MAIN DASHBOARD
// ========================
export default function App() {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [selectedMember, setSelectedMember] = useState(null);
  const [isPending, startTransition] = useTransition();

  // useDeferredValue - deferred search
  const deferredSearch = useDeferredValue(searchQuery);

  // useMemo - memoizing the filtered list
  const filteredCrew = useMemo(() => {
    return ALL_CREW.filter(member => {
      const matchesSearch = member.name.toLowerCase().includes(deferredSearch.toLowerCase()) ||
                            member.role.toLowerCase().includes(deferredSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || member.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [deferredSearch, statusFilter]);

  // useMemo - calculating statistics
  const stats = useMemo(() => ({
    total: ALL_CREW.length,
    active: ALL_CREW.filter(m => m.status === 'Active').length,
    onMission: ALL_CREW.filter(m => m.status === 'On mission').length,
    avgRating: (ALL_CREW.reduce((sum, m) => sum + parseFloat(m.rating), 0) / ALL_CREW.length).toFixed(1),
  }), []);

  // useCallback - stable function reference for memoized components
  const handleSelect = useCallback((member) => {
    setSelectedMember(member);
  }, []);

  // TODO 2: Use useCallback for handleStatusChange
  // to prevent re-renders of the filtering components
  const handleStatusChange = (status) => {
    startTransition(() => {
      setStatusFilter(status);
    });
  };

  // TODO 3: Use useMemo to compute topPerformers
  // (top 5 members by rating from the filtered list)
  // sort changes the array in place, so we sort a copy: otherwise the table would also be ordered by rating
  const topPerformers = [...filteredCrew]
    .sort((a, b) => parseFloat(b.rating) - parseFloat(a.rating))
    .slice(0, 5);

  const STATUSES = ['all', 'Active', 'On mission', 'Resting', 'Training'];

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #0a0e27 0%, #1a1a3e 100%)',
      padding: '20px', fontFamily: 'monospace', color: '#e0e1dd',
    }}>
      <h1 style={{ color: '#00d4ff', textAlign: 'center', margin: '0 0 4px' }}>
        Fleet Command Center
      </h1>
      <p style={{ color: '#778da9', textAlign: 'center', marginBottom: '20px', fontSize: '13px' }}>
        Dashboard with React.memo | useMemo | useCallback | useTransition | useDeferredValue
      </p>

      {/* Statistics */}
      <div style={{
        display: 'flex', gap: '12px', justifyContent: 'center',
        marginBottom: '20px', flexWrap: 'wrap',
      }}>
        <StatCard icon="β—†" label="Total crew" value={stats.total} color="#00d4ff" />
        <StatCard icon="OK" label="Active" value={stats.active} color="#4ecdc4" />
        <StatCard icon="β–²" label="On mission" value={stats.onMission} color="#ffd700" />
        <StatCard icon="β—†" label="Average rating" value={stats.avgRating} color="#ff6b4a" />
      </div>

      <div style={{ maxWidth: '800px', margin: '0 auto' }}>
        {/* Search and filters */}
        <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', flexWrap: 'wrap' }}>
          <input
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            placeholder="Search crew member..."
            style={{
              flex: 1, minWidth: '200px', padding: '10px 14px',
              background: '#0d1b2a', border: '1px solid #1a3a5c',
              borderRadius: '8px', color: '#e0e1dd', fontSize: '14px',
            }}
          />
          {STATUSES.map(status => (
            <button
              key={status}
              onClick={() => handleStatusChange(status)}
              style={{
                padding: '8px 14px',
                background: statusFilter === status ? '#1a3a5c' : 'transparent',
                border: `1px solid ${statusFilter === status ? '#00d4ff' : '#1a3a5c'}`,
                borderRadius: '6px', fontSize: '12px',
                color: statusFilter === status ? '#00d4ff' : '#778da9',
                cursor: 'pointer',
              }}
            >
              {status === 'all' ? 'All' : status}
            </button>
          ))}
        </div>

        {isPending && (
          <div style={{ color: '#00d4ff', fontSize: '12px', marginBottom: '8px' }}>
            Filtering...
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: '16px' }}>
          {/* Crew table */}
          <div>
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 100px 90px 60px 50px',
              padding: '8px 14px', fontSize: '11px', color: '#556677',
              borderBottom: '2px solid #1a3a5c', textTransform: 'uppercase',
            }}>
              <span>Name</span><span>Role</span><span>Status</span>
              <span style={{ textAlign: 'center' }}>Missions</span>
              <span style={{ textAlign: 'center' }}>Rating</span>
            </div>
            <div style={{ maxHeight: '350px', overflow: 'auto' }}>
              {filteredCrew.slice(0, 50).map(member => (
                <CrewRow
                  key={member.id}
                  member={member}
                  onSelect={handleSelect}
                />
              ))}
            </div>
            <div style={{ padding: '8px 14px', fontSize: '12px', color: '#556677' }}>
              Showing {Math.min(50, filteredCrew.length)} of {filteredCrew.length} results
            </div>
          </div>

          {/* Side panel */}
          <div>
            <DetailPanel selectedMember={selectedMember} />

            <div style={{ marginTop: '16px' }}>
              <h4 style={{ color: '#ffd700', margin: '0 0 8px', fontSize: '13px' }}>
                Top 5 - highest rating
              </h4>
              {topPerformers.map((m, i) => (
                <div key={m.id} style={{
                  display: 'flex', justifyContent: 'space-between',
                  padding: '6px 10px', fontSize: '12px',
                  background: i === 0 ? 'rgba(255, 215, 0, 0.06)' : 'transparent',
                  borderRadius: '4px',
                }}>
                  <span style={{ color: '#c0c8d0' }}>
                    {i + 1}. {m.name}
                  </span>
                  <span style={{ color: '#ffd700' }}>{m.rating}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

  1. Project to submitMentor Project: Galactic Core Performance Laboratory
  2. VideoVideo: Module Summary

Useful articles