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.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

Solve in

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

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.