GDG Logo

Game Dev with React Workshop

Timer Component

The Timer component manages and displays the game duration in minutes and seconds format. It automatically starts when the game begins and stops when the game ends.

1. File Declaration and Imports

import React, { useEffect } from 'react';
import { useAtom } from 'jotai';
import { timerAtom } from '../store/atom';

File setup and essential imports: - React and useEffect for component functionality - useAtom from Jotai for state management - timerAtom from store for managing the game timer state

2. Component Declaration and State Setup

const Timer = ({ gameOver }) => {
  const [time, setTime] = useAtom(timerAtom);

Component initialization: - Accepts gameOver prop to control timer state - Uses Jotai's useAtom to manage timer state - Destructures both time value and setter function

3. Timer Logic Implementation

  useEffect(() => {
    if (!gameOver) {
      const timer = setInterval(() => {
        setTime(prev => prev + 1);
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [gameOver, setTime]);

Timer implementation using useEffect: - Checks if game is active (!gameOver) - Sets up interval to increment time every second - Uses functional update pattern for reliable state updates - Includes cleanup function to prevent memory leaks - Dependencies track game state and time setter

4. Time Formatting Function

  const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

Time formatting utility function: - Converts total seconds into minutes and seconds - Uses Math.floor for minute calculation - Uses modulo operator for remaining seconds - Pads numbers with leading zeros for consistent format - Returns time in MM:SS format

5. Component Render

  return (
    <div className="timer">
        Time: {formatTime(time)}
    </div>
  );
};

export default Timer;

Component rendering: - Renders a div with 'timer' class for styling - Displays formatted time using the formatTime function - Exports component for use in GameBoard