Skip to content

re-compose/traffic-light-react

Repository files navigation

Traffic Light — React useEffect and Timers

Welcome to your traffic light composition! I'm your mentor, and I'll guide you step-by-step to learn React useEffect, timers, and state machines with a modern TypeScript setup.

Difficulty: Beginner
Estimated time: 1–2 hours

Summary

Build a traffic light component that automatically cycles through red, yellow, and green lights at predetermined intervals. Learn React useEffect, setTimeout, cleanup functions, and state machine patterns.

What is a Traffic Light Component?

A traffic light is a state machine that cycles through different colors (states) at fixed intervals. Think of it like a timer that automatically switches between colors—green means go, yellow means caution, and red means stop. In programming, this teaches you how to manage time-based state transitions and handle side effects in React.

Why Traffic Lights Matter:

  • They demonstrate state machines—a fundamental programming pattern
  • Building one teaches you React useEffect and timer management
  • They show how to handle cleanup to prevent memory leaks
  • Understanding timers is essential for animations, polling, and scheduled tasks
  • They're a common interview question that tests your understanding of React hooks

Learning Outcomes

  • Understand how to use useEffect for side effects
  • Implement timers with setTimeout and cleanup with clearTimeout
  • Build a state machine pattern in React
  • Manage component lifecycle and prevent memory leaks
  • Use TypeScript interfaces for component configuration

Prerequisites

  • Node.js 18+ installed
  • Basic knowledge of React and TypeScript
  • Comfort with the terminal and npm
  • Understanding of useState from previous compositions

Before You Begin (Environment Checklist)

  • npm --version works
  • Port 5173 available (Vite dev server)
  • Git configured (git --version)
  • Editor with TypeScript and ESLint plugins

Getting Started

Step 1: Install dependencies

npm install

Step 2: Start the app

  • Frontend-only:
    • npm run dev → open http://localhost:5173

Step 3: Run tests

  • Unit/Integration (Jest):
    npm run test
  • Watch mode:
    npm run test:watch

Step 4: Format and lint

npm run format
npm run lint

Project Structure

traffic-light/
├── client/
│   ├── index.html
│   └── src/
│       ├── App.tsx
│       ├── TrafficLight.tsx
│       ├── main.tsx
│       ├── styles.css
│       └── __tests__/
├── docs/
│   ├── description.md
│   └── solution.md
├── README.md
├── vite.config.ts
├── tsconfig.json
├── jest.config.js
└── eslint.config.js

Standard Ports

  • Frontend (Vite): http://localhost:5173

Scripts (package.json)

  • dev: Vite dev server
  • build: tsc -b && vite build
  • lint: ESLint check
  • typecheck: TypeScript type checks
  • format: Prettier write
  • format:check: Prettier check
  • test: Jest (unit/integration)
  • test:watch: Jest watch mode
  • preview: Vite preview (built app)

Configuration Files

Always include:

  • vite.config.ts (with @ alias to client/src)
  • jest.config.js (client jsdom project)
  • eslint.config.js
  • .prettierrc
  • tsconfig.json (paths @/*client/src/*)
  • components.json (shadcn/ui)
  • Dockerfile (for CI/grading)

Requirements Checklist

Frontend

  • Create config object with red, yellow, green colors
  • Each color has backgroundColor, duration, and next properties
  • Red light: 4000ms duration, next: 'green'
  • Yellow light: 500ms duration, next: 'red'
  • Green light: 3000ms duration, next: 'yellow'
  • TrafficLight component accepts config prop
  • Component uses useState to track current color
  • Component uses useEffect to set up timer
  • Timer transitions to next color after duration
  • Cleanup function clears timer on unmount
  • Only active light has backgroundColor style
  • Component has aria-label for accessibility
  • No console errors

Acceptance Criteria

Your solution is complete when:

  1. ✓ Traffic light renders with three lights
  2. ✓ Lights cycle through green → yellow → red → green
  3. ✓ Each light displays for the correct duration
  4. ✓ Timer cleanup prevents memory leaks
  5. ✓ No console errors
  6. ✓ All tests pass
  7. ✓ Type checks pass (npm run typecheck)
  8. ✓ Lint passes (npm run lint)

Grading Criteria

  • Functionality: 50%
  • Code Structure and Types: 20%
  • useEffect and Cleanup: 20%
  • Code Quality (lint/format): 10%

Hints

Start simple, then refine. Layered guidance:

  • First nudge: "Use useState to track the current color state."
  • Deeper: "Use useEffect with setTimeout to transition colors after the duration."
  • Deepest: "Remember to return a cleanup function from useEffect that calls clearTimeout to prevent memory leaks."

Troubleshooting

  • Problem: npm install fails
    Solution: Ensure Node 18+ is installed and try rm -rf node_modules && npm cache clean --force && npm install.

  • Problem: Frontend 5173 already in use
    Solution: Stop the conflicting process or change the Vite port in vite.config.ts.

  • Problem: Tests fail unexpectedly
    Solution: Run npm run test:watch and read failing test expectations; ensure you're using fake timers correctly.

  • Problem: Timer doesn't cleanup
    Solution: Make sure your useEffect returns a cleanup function that calls clearTimeout(timerId).

  • Problem: Component updates after unmount
    Solution: Ensure cleanup function is properly clearing the timer to prevent "setState on unmounted component" errors.


Git Workflow

Recommended flow:

  1. Create a feature branch:
    git checkout -b feature/traffic-light
  2. Commit with conventional messages:
    git add .
    git commit -m "feat: implement traffic light component"
  3. Push:
    git push origin feature/traffic-light

Code Quality

  • Run npm run lint and npm run format before committing
  • Prefer explicit types; avoid any when possible
  • Organize imports: external → internal → types
  • Use @/ path aliases for internal modules

TODO Conventions

  • Use // TODO: (short, task-focused)
  • Place inline where the change is needed
  • Keep TODOs concise

Key Concepts You'll Learn

  • React useEffect hook for side effects
  • setTimeout and clearTimeout for timers
  • Cleanup functions to prevent memory leaks
  • State machine pattern
  • Component lifecycle management

Next Steps

After finishing:

  • Add pause/resume functionality
  • Support custom color sequences
  • Add sound effects for each transition
  • Implement horizontal layout option
  • Add animation transitions between colors

Documentation (docs/description.md)

Include:

  • Problem Statement and Details
  • Use Cases (Primary/Secondary)
  • Constraints (Technical + Business Rules)
  • Test Data (schemas and examples)
  • Requirements Checklist
  • Examples and Edge Cases
  • Acceptance Criteria
  • Hints

Good luck, and happy building!
Your React Development Mentor

About

traffic-light composition - react variant

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors