How to implement a countdown timer in React?

To implement a countdown timer in React, you can follow these steps:

  1. Create a new React component for the countdown timer.
import React, { useState, useEffect } from 'react'; const CountdownTimer = ({ seconds }) => { const [timeLeft, setTimeLeft] = useState(seconds); useEffect(() => { const timer = setInterval(() => { setTimeLeft(timeLeft => timeLeft - 1); }, 1000); return () => clearInterval(timer); }, []); return ( <div> <h1>{timeLeft}</h1> </div> ); } export default CountdownTimer;
  1. Use the created CountdownTimer component in your main App component.
import React from 'react'; import CountdownTimer from './CountdownTimer'; const App = () => { return ( <div> <h1>Countdown Timer</h1> <CountdownTimer seconds={60} /> </div> ); } export default App;
  1. In the example above, the CountdownTimer component takes a prop seconds to specify the initial countdown time in seconds. The component uses the useState hook to keep track of the time left and the useEffect hook to update the countdown timer every second.

  2. You can customize the countdown timer by adding CSS styles or additional functionality as needed for your application.