Building a Pomodoro Timer with Tauri using React and Vite
Tags: react, webdev
Published: 2022-09-14 17:18:40

**Written by [Rahul Padalkar](https://blog.logrocket.com/author/rahulpadalkar/)✏️**

[Tauri](https://tauri.app/) is a set of tools that lets you build cross-platform desktop apps using frontend frameworks. When combined with React and Vite, it can be used to build extremely fast binaries for all desktop platforms. 

Developers can use Tauri to write secure, lean, and fast cross-platform desktop apps with web technologies. [Electron](https://www.electronjs.org/) has for many developers typically been the go-to framework for these apps, but Tauri is now well positioned to compete. 

In this post, we will build a simple Pomodoro timer, and I invite you to follow along with this tutorial at your own pace.

*   [What is Tauri?](#what-is-tauri)
*   [Prerequisites](#prerequisites)
*   [Scaffold a Tauri app with create-tauri-app](#scaffold-a-tauri-app-with-create-tauri-app)
*   [Building the frontend](#building-the-frontend)
*   [Triggering a notification and adding a reset timer button](#triggering-a-notification-and-adding-a-reset-timer-button)
*   [Building the app](#building-th-eapp)

## What is Tauri?

It is “[blazingly fast](https://tauri.app/about/benchmarks/)” (their words, not mine; but follow the link to see benchmarks and decide for yourself) because it uses Rust as its backend (vs. Node), produces smaller binaries, and is more secure than Node is. 

It uses the WebView that the underlying OS provides to render the application’s UI — this is one of the reasons why the application binaries are smaller (as compared to electron). [The WRY library](https://github.com/tauri-apps/wry) from the Tauri toolkit provides a unified interface to interact with WebViews provided by different operating systems. The WRY library uses the Tao crate for cross-platform window management. 

Tauri brings it all together and enables developers write powerful and performant desktop applications.

## Prerequisites

Before we get started, we need to install a couple of things.

### Rust

To install Rust, open your terminal and run: `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh` 

If you are on Windows, please follow [these instructions](https://forge.rust-lang.org/infra/other-installation-methods.html).

### npm

npm is a package manager for Node. It comes bundled with Node, so if you have Node installed on your system, you are likely to have npm as well. 

If you don’t have Node, install it using [Homebrew](https://brew.sh/), 

`brew install node` 

With npm and Rust installed, we are all set to start developing apps using Tauri!

## Scaffold a Tauri app with create-tauri-app

Since the prerequisites are now installed, we can start developing our Pomodoro timer desktop app. The folks at Tauri have made scaffolding an app super easy with the [**create-tauri-app**](https://www.npmjs.com/package/create-tauri-app) npm package. 

To get started, run:

```rust
npx create-tauri-app
```

After running this command, you will be required to enter some information:

*   The name of the project
*   The title of the window in which the app will load
*   The UI recipe
*   Template to use

For this tutorial app, I went with the following, found below 👇

*   Name of the project as “pomodoro”
*   Title of the window as “Pomodoro Timer App”
*   UI recipe as “create-vite”
*   Template to use “react-ts”

![Tauri Project Dependencies Installation](https://blog.logrocket.com/wp-content/uploads/2022/09/tauri-project-dependecies-installation.png) 

Hitting **Enter** will then install all the necessary packages and output a scaffolded project under the folder with the same name as the project name. 

We are now all set to run the project for the very first time! 

To run the project, run:

```bash
cd pomodoro // cding into the project folder
npm run tauri dev //running the app
```

This will first start the frontend server and then will download crates (if necessary) and compile the Rust backend. Once compiled without any errors, the app will start and you will be greeted with the something like this: 

![Vite And React App Example](https://blog.logrocket.com/wp-content/uploads/2022/09/vite-and-react-app-example.png) 

The project folder contains a lot of important files and folders. The two that we will deal with in this tutorial are:

*   `src` folder and
*   `src-tauri/tauri.config.json` file

(Note: Running the app for the first time will take some time, as the app needs to download and compile the necessary rust crates) (Note: For folks using macOS for development — if you run the command to start the app and the app window appears over a fullscreen app, you won’t be able to move the app window. This is a known bug and can be tracked [here](https://github.com/tauri-apps/tauri/issues/4310))

## Building the frontend

We will use [ChakraUI](https://chakra-ui.com/) for UI components and styling. To setup ChakraUI, follow their [getting started guide](https://chakra-ui.com/getting-started). 

We will be building the UI below. ![Timer App UI Example](https://blog.logrocket.com/wp-content/uploads/2022/09/timer-app-ui-example.png) Below are the requirements for our app:

*   Should have a **Start** and **Pause** button, which starts and stops the timer.
*   Once the timer hits **0**, trigger a notification to the user.
*   Option to choose interval lengths, i.e.; 15 mins, 30 minutes, and 60 minutes.
*   A **Reset** button to reset the timer to the initial value.

To start, head over to `src/App.tsx`.

```rust
// src/App.tsx
import { Button, Flex, Text } from "@chakra-ui/react";
import { useEffect, useState } from "react";

function App() {
  const [time, setTime] = useState(0);
  const [timerStart, setTimerStart] = useState(false);
  const buttons = [
    {
      value: 900,
      display: "15 minutes",
    },
    {
      value: 1800,
      display: "30 minutes",
    },
    {
      value: 3600,
      display: "60 minutes",
    },
  ];
  const toggleTimer = () => {
    setTimerStart(!timerStart);
  };
  useEffect(() => {
    const interval = setInterval(() => {
      if (timerStart) {
        if (time > 0) {
          setTime(time - 1);
        } else if (time === 0) {
          // TODO: Send notification to user.
          clearInterval(interval);
        }
      }
    }, 1000);
    return () => clearInterval(interval);
  }, [timerStart, time]);
  return (
    <div className="App" style={{ height: "100%" }}>
      <Flex
        background="gray.700"
        height="100%"
        alignItems="center"
        flexDirection="column"
      >
        <Text color="white" fontWeight="bold" marginTop="20" fontSize="35">
          Pomodoro Timer
        </Text>
        <Text fontWeight="bold" fontSize="7xl" color="white">
          {`${
            Math.floor(time / 60) < 10
              ? `0${Math.floor(time / 60)}`
              : `${Math.floor(time / 60)}`
          }:${time % 60 < 10 ? `0${time % 60}` : time % 60}`}
        </Text>
        <Flex>
          <Button
            width="7rem"
            background="tomato"
            color="white"
            onClick={toggleTimer}
          >
            {!timerStart ? "Start" : "Pause"}
          </Button>
          {/* TODO: Add Button to reset timer */}
        </Flex>
        <Flex marginTop={10}>
          {buttons.map(({ value, display }) => (
            <Button
              marginX={4}
              background="green.300"
              color="white"
              onClick={() => {
                setTimerStart(false);
                setTime(value);
              }}
            >
              {display}
            </Button>
          ))}
        </Flex>
      </Flex>
    </div>
  );
}
export default App;
```

Here, we are using [ChakraUI](https://chakra-ui.com/)’s built in components for setting up the layout for buttons and text. 

The `setTimeout` in the `useEffect` hook drives the UI by setting state every passing second. 

The effect re-runs:

*   When the user clicks on the duration buttons (this sets both the `timerStart` and `time` state values)
*   When the user clicks on the **Start**/**Pause** buttons. (this sets the `timerStart` state value)
*   Every passing second. (the `setTimeout` triggers an update to the `time` value, see line number 29)

To display the time in consistent format (mm:ss), we need to do some math gymnastics. 

It’s certainly not perfect, but it does the job. There are two to-dos here are:

*   **Adding a Reset button**
    *   On clicking this, a native dialog triggers, asking the user to confirm the action
*   **Adding a notification trigger**
    *   When the timer hits 0, a notification needs to be sent to the user

But, before we start working on these items, we need to add the native APIs we will be calling in the `src-tauri/tauri.config.json` file. If we don’t do this step, we won’t be able to trigger the native elements. 

So, head over to `src-tauri/tauri.config.json` and add this to `tauri.allowlist`

```rust
  "tauri": {
    "allowlist": {
      // other allowed items
      "notification": {
        "all": true
      },
      "dialog": {
        "all": true
      }
    }    
  }
```

(Note: For the sake of simplicity, everything is allowed for `dialog` and `notification`. We can be more specific to avoid unwanted access)

## Triggering a notification and adding a reset timer button

```rust
// src/App.tsx
import { Button, Flex, Text } from "@chakra-ui/react";
import { useEffect, useState } from "react";
+ import { sendNotification } from "@tauri-apps/api/notification";
+ import { ask } from "@tauri-apps/api/dialog";
function App() {
  const [time, setTime] = useState(0);
  const [timerStart, setTimerStart] = useState(false);
  const buttons = [
    {
      value: 900,
      display: "15 minutes",
    },
    {
      value: 1800,
      display: "30 minutes",
    },
    {
      value: 3600,
      display: "60 minutes",
    },
  ];
  const toggleTimer = () => {
    setTimerStart(!timerStart);
  };
+ const triggerResetDialog = async () => {
+   let shouldReset = await ask("Do you want to reset timer?", {
+     title: "Pomodoro Timer App",
+     type: "warning",
+   });
+   if (shouldReset) {
+     setTime(900);
+     setTimerStart(false);
+   }
+ };
  useEffect(() => {
    const interval = setInterval(() => {
      if (timerStart) {
        if (time > 0) {
          setTime(time - 1);
        } else if (time === 0) {
+         sendNotification({
+           title: `Time's up!`,
+           body: `Congrats on completing a session!🎉`,
+         });
          clearInterval(interval);
        }
      }
    }, 1000);
    return () => clearInterval(interval);
  }, [timerStart, time]);
  return (
    <div className="App" style={{ height: "100%" }}>
      <Flex
        background="gray.700"
        height="100%"
        alignItems="center"
        flexDirection="column"
      >
        <Text color="white" fontWeight="bold" marginTop="20" fontSize="35">
          Pomodoro Timer
        </Text>
        <Text fontWeight="bold" fontSize="7xl" color="white">
          {`${
            Math.floor(time / 60) < 10
              ? `0${Math.floor(time / 60)}`
              : `${Math.floor(time / 60)}`
          }:${time % 60 < 10 ? `0${time % 60}` : time % 60}`}
        </Text>
        <Flex>
          <Button
            width="7rem"
            background="tomato"
            color="white"
            onClick={toggleTimer}
          >
            {!timerStart ? "Start" : "Pause"}
          </Button>
+         <Button
+           background="blue.300"
+           marginX={5}
+           onClick={triggerResetDialog}
+         >
+           Reset
+         </Button>
        </Flex>
        <Flex marginTop={10}>
          {buttons.map(({ value, display }) => (
            <Button
              marginX={4}
              background="green.300"
              color="white"
              onClick={() => {
                setTimerStart(false);
                setTime(value);
              }}
            >
              {display}
            </Button>
          ))}
        </Flex>
      </Flex>
    </div>
  );
}
export default App;
```

Tauri offers a [JS/TS API](https://www.npmjs.com/package/@tauri-apps/api) package for calling functions from the Rust backend. The necessary packages are already installed by the `create-tauri-app` utility, so we can directly import the npm package and use it in our frontend code. 

**For triggering a notification:**

*   Import the `sendNotification` function from the notification module
*   Call the function in the frontend code (see line 42). More on the API [here](https://tauri.app/v1/api/js/modules/notification#sendnotification)

**For triggering a dialog:**

*   Import the `ask` function from the dialog module
*   Call the function in the forntend code. The first parameter is the text that will appear in the dialog box (see line 27). More on the API [here](https://tauri.app/v1/api/js/modules/dialog#ask)
*   Since it requires user input, the function returns a promise with a boolean value, so we can `await` it to get the value the user clicked on
*   If the user accepts, we reset the time value to 15 minutes and stop the timer if it is running already

**Finally to run the app, run:** 

`npm run tauri dev` 

![Pomodoro Timer Final](https://blog.logrocket.com/wp-content/uploads/2022/09/pomodoro-timer-final.gif)

## Building the app

Building the application for distribution can be achieved by running, 

`cargo tauri build` 

This will build the application and create a binary under `src-tauri/target/release` 

Now, the app is ready to be [published](https://tauri.app/v1/guides/distribution/publishing/)!

## Conclusion

That’s it! Thank you for reading my walkthrough tutorial on building an app using Tauri with Vite and React. 

If you have any questions/suggestions feel free to reach out to me on twitter [@rahulnpadalkar](https://twitter.com/rahulnpadalkar). You can find the github repo with [all the code here](https://github.com/rahulnpadalkar/PomodoroTimer).

---

##[LogRocket](https://www2.logrocket.com/react-performance-monitoring) proactively surfaces and diagnoses the most important issues in your React apps

[![React Performance Monitoring](https://blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png)](https://lp.logrocket.com/blg/signup)

Thousands of engineering and product teams use [LogRocket](https://www2.logrocket.com/react-performance-monitoring) to reduce the time it takes to understand the root cause of technical and usability issues in their React apps. With LogRocket, you'll spend less time on back-and-forth conversations with customers and remove the endless troubleshooting process. LogRocket allows you to spend more time building new things and less time fixing bugs.

Proactively fix your React apps — try [LogRocket](https://www2.logrocket.com/react-performance-monitoring) today.