Sobes.tech
Junior — Senior

Review and refactoring of a timer in a React component

livecode

Task condition

This task presents a React component implementing a simple timer. The goal is to perform a code review and refactor the code to improve readability and structure, as well as eliminate potential issues.

What needs to be done:

  • Analyze the current implementation, identify areas where the code can be simplified or made more reliable.
  • Rewrite the component using more understandable variable and function names, and remove duplicated logic.
  • Add comments if necessary, improve effect handling and resource cleanup.
  • Preserve functionality: the "Start/Pause" button should start and pause the timer, the "Stop" button should reset it, and every fifth tick should be visually highlighted.
import { useEffect, useRef, useState } from "react";
import "./App.css";

export default function App() {
  const [isRunning, setIsRunning] = useState(false);
  const [seconds, setSeconds] = useState(0);

  const timerRef = useRef();

  const handleStop = () => {
    setSeconds(0);
    setIsRunning(false);
    clearInterval(timerRef.current);
    timerRef.current = null;
  };

  const handleToggle = () => {
    if (isRunning) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    } else {
      timerRef.current = setInterval(() => {
        setSeconds((prev) => prev + 1);
      }, 1000);
    }
    setIsRunning(!isRunning);
  };

  useEffect(() => {
    if (seconds % 5 === 0 && seconds !== 0) {
      document.querySelector(".timer").classList.add("pulsate");
    }
  }, [seconds]);

  return (
    <div className="main">
      <div>
        <button onClick={handleToggle}>{isRunning ? "Pause" : "Start"}</button>
        <button onClick={handleStop}>Stop</button>
      </div>
      <div className="timer">{seconds}</div>
    </div>
  );
}

Expected result: After refactoring, the code should be easier to understand, free of unnecessary side effects, and work correctly in all browsers.