React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a Pomodoro timer app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app pomodoro-timer
with NPM to create our React project.
Create the Pomodoro Timer App
To create the Pomodoro timer app, we write:
import React, { useEffect, useState } from "react";
export default function App() {
const [secondsLeft, setSecondsLeft] = useState(25 * 60);
const [timer, setTimer] = useState();
const start = () => {
const timer = setInterval(() => {
setSecondsLeft((secondsLeft) => secondsLeft - 1);
if (secondsLeft === 0) {
clearInterval(timer);
}
}, 1000);
setTimer(timer);
};
useEffect(() => {
if (secondsLeft === 0) {
clearInterval(timer);
}
}, [secondsLeft, timer]);
useEffect(() => {
return () => clearInterval(timer);
}, [timer]);
return (
<div className="App">
<h1>Pomodoro Timer</h1>
<button onClick={start}>start</button>
<div>{secondsLeft} seconds left</div>
</div>
);
}
We define the secondsLeft
state set to 25 * 60
seconds as the initial value.
Also, we define the timer
state set to undefined
as the initial value.
The start
function creates a timer with the setInterval
function.
The callback sets the secondsLeft
state by decrementing it by 1.
If secondsLeft
is 0, then we call clearInterval
to clear the timer.
We run the setIntrval
callback every second.
Also, we have the useEffect
callback that returns a function to call clearInterval
to clear the timer when we unmount the component.
Below that, we have a button to start the timer when we click on it.
And below that, we show the secondsLeft
to the user.
Conclusion
We can create a Pomodoro timer easily with React and JavaScript.