Skip to solution
easyMachine Coding

Build a Traffic Light

1.0k views
01

Understand the problem

Build a traffic light that cycles red → green → yellow automatically.

ReactTimersState Machine
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Solve in

Building a Traffic Light in React

This tutorial guides you through creating a simple traffic light component in React that automatically cycles through red, green, and yellow.

Mental Model

The core idea is to use React's useState hook to manage the current light color and useEffect with setTimeout to tri

Solution ready — 2 min read

Classified // press E to declassify

04

React solution

Complete solutionRun Playground
import React, { useState } from 'react';
import TrafficLight from './src/TrafficLight';

export default function App() {
  // State to observe the current light from the TrafficLight component (optional, for demo purposes)
  // In a real app, the TrafficLight would likely manage its own state internally
  // or receive props to control its behavior.
  const [currentLightColor, setCurrentLightColor] = useState('red');

  // This is a simplified way to 'observe' the state for the demo. 
  // A more robust solution might involve the TrafficLight component exposing a callback prop.
  // For this exercise, we'll just let the TrafficLight run independently.

  return (
    <div
      style={{
        fontFamily: 'sans-serif',
        textAlign: 'center',
        padding: '20px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '20px',
      }}
    >
      <h1>Traffic Light Demo</h1>
      <TrafficLight />
      <p>The traffic light is cycling automatically.</p>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 6 of 87 decoded in the Frontend Machine Coding track. One more won't hurt.

Back to track