i-logoCreated with Sketch.Navigate back to the homepage

ReasonML with React Hooks Tutorial — Building a Pomodoro Timer

Ian Wilson
April 15th, 2019 · 6 min read

ReasonML is a programming language that combines the simplicity of JavaScript with the performance of OCaml. JavaScript programmers should give ReasonML a try. Reason’s inherits OCaml’s typesystem as well as the approachability of JavaScript.

With ReasonReact and BuckleScript, we can compile Reason code to JavaScript that works like good old React.

But that’s not all, things are getting even better for the Reason ecosystem. Earlier last week, ReasonReact version 0.7.0 dropped, with support for React hooks. We can now build robust components with React hooks that:

  • eliminate duplicated lifecycle logic (like in componentDidMount, componentDidUpdate, and componentWillUnmount)
  • eliminate the need for complicated patterns like higher-order components or render props
  • allow easier refactoring of stateful components

Think for a moment about that last point, what else give us easier refactorability?

A rock solid typesystem and a helpful compiler!

Today, we’re going to build a Pomodoro Timer like this using Reason and React.

A pomodoro timer allows you to set a timer for say 25 or 30 minutes that lets you know when to stop working. Because sometimes taking a break is good, and you better believe I’m using one while writing this.

Initializing a Project

The first step is to install BuckleScript, a tool that will compile our Reason code to JavaScript.

1npm install -g bs-platform

After that, we can scaffold our project with the init command, and setting the theme to react-hooks.

1bsb -init pomodoro-timer -theme react-hooks
2cd pomodoro-timer && npm install

Now that our project set up, we can mention our folder layout. Our Reason code belongs in the src directory. Where we usually have an index.js file in a JavaScript React project, we have an Index.re file. These files serve the same purpose: render the app root.

Since our code will compile to JavaScript, I still like to have a bundler like Webpack to bundle those files.

Tip: It is generally considered a best practice to keep your folder structure as flat as possible with ReasonML, using captialized file names (like Timer.re). See the [ReasonML docs](https://reasonml.github.io/docs/en/project-structure#folders) for a discussion on project structure.

Running the code

Before I clean up the environment, let us try running the code. This will need two or three separate terminal tabs:

1# in one tab
2npm start

This runs bsb -make-world -w which compiles your Reason files on every change. It does this quickly, mind you.

1# in another tab
2npm run webpack

This command takes our compiled JavaScript and spits out a bundle that we can then open in a browser using:

1open build/index.html

I prefer use a static file server like zeit/serve.

1# install `serve` globally
2npm i -g serve
4# serve it!
5serve build/

initial project

Cleaning up the Environment

I want to clean up the default project structure before writing an implementation.

  1. Remove the Component1.re and Component2.re files, we will not be using these. You can still read them and try to making sense of how hooks are working in our new environment.
  2. Replace index.html with the following:
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <title>Pomodoro Timer</title>
6 </head>
7 <body>
8 <div id="root"></div>
9 <script src="Index.js"></script>
10 </body>
  1. Replace Index.re with the following:
1ReactDOMRe.renderToElementWithId(<Timer />, "root");
  1. Open up bsconfig.json and change the field “in-source” from true to false. This will output our compiled JavaScript into the lib/js directory. I prefer this over leaving them inside of our root src directory.

  2. Tell webpack to build from the new location by changing webpack.config.js to the following:

1module.exports = {
2 entry: './lib/js/src/Index.bs.js'
3 // rest of webpack config

And now with all out that taken care of, we can begin the fun part, the implementation.

Building a Stateless Component

After cleaning up, notice that we are trying to render a Timer component but we have not even defined one. Let us write a stateless component to render to the page.

2let make = () => {
3 <div> {ReasonReact.string("One day this will be a timer")} </div>;

I want to highlight how simple this code is. Writing a stateless React component in the previous version was more verbose:

2let component = ReasonReact.statelessComponent("Timer");
3let make = () => {
4 ...component,
5 render: _children => <div> {ReasonReact.string("One day this will be a timer")} </div>;

Even compared to regular JavaScript with React, this new syntax is incredibly slick. With Reason projects, we do not need to layer imports on top of the file every time we make a new file.

The useReducer Hook

Now we are going to introduce some state into this equation. We do not have any “class” components, we are still using functional components. But now we are going to use React hooks to compose a solution.

For our timer, we need to keep track of at least two things:

  1. The seconds on the clock
  2. Whether it is ticking or not

When we consider any timer, we usually have three buttons: Start, Stop, and Reset. These map to directly to user interactions, but there is one more: the Tick itself. Even though the tick is not controlled by the user, it is still an action that should return a new state for our reducer.

At the top of Timer.re, where we will build this whole app, add the following:

1type state = {
2 seconds: int,
3 isTicking: bool
6type action =
7 | Start
8 | Stop
9 | Reset
10 | Tick;

How easy it is, to implement an application after you have described your states needs and actions!

Next we’ll update our make function to use a reducer:

2let make = () => {
3 let (state, dispatch) =
4 React.useReducer(
5 (state, action) =>
6 switch (action) {
7 | Start => {...state, isTicking: true}
8 | Stop => {...state, isTicking: false}
9 | Reset => {...state, seconds: 30}
10 | Tick => {...state, seconds: state.seconds - 1}
11 },
12 {isTicking: false, seconds: 30},
13 );
15 <div>
16 {ReasonReact.string(
17 "There are " ++ string_of_int(state.seconds) ++ " on the clock",
18 )}
19 </div>;

The syntax is like that of ReactJS. The useReducer function returns a tuple as opposed an array. This is because JavaScript does not know what the heck a tuple is. We make sure to handle each of our action types inside this reducer, returning a whole copy of the state.

The second argument to useReducer is the initial state of the reducer. It would make sense for the time to receive the initial time as a prop but I’ll leave it this way for now.

Now we need a way to invoke these actions. Let us start with the Tick because it is the most complicated bit.

The useEffect hook

To update the timer every second, we need to create an effect. In the JavaScript world, this means putting a callback function within setInterval.

Let us add this hook between the useReducer function and the returned JSX.

1React.useEffect0(() => {
2 let timerId = Js.Global.setInterval(() => dispatch(Tick), 1000);
3 Some(() => Js.Global.clearInterval(timerId));

If you recall the way useEffect works:

  • The first argument is a callback function that runs when the component mounts, updates, or unmounts.
  • Optionally, the callback function can return another function that performs cleanup. This includes unsubscribing from sockets or clearing a setInterval so it does not persist forever.

If you run the code and refresh your browser, you’ll see that our timer is going to run indefinitely.

It should not do this, so lets update our reducer again to account for whether the isTicking flag is true or false. We will also make sure that seconds are greater than zero so we do not go negative.

1let (state, dispatch) =
2 React.useReducer(
3 (state, action) =>
4 switch (action) {
5 | Start => {...state, isTicking: true}
6 | Stop => {...state, isTicking: false}
7 | Reset => {...state, seconds: 30}
8 | Tick => state.isTicking && state.seconds > 0
9 ? {...state, seconds: state.seconds - 1} : state
10 },
11 {isTicking: false, seconds: 30},
12 );

Now you can verify this by setting isTicking to true and seconds to 3. Lovely, this app is functional now. If you wanted to actually use it, refresh your browser and watch it count down.

Interactivity with Buttons

To make this Timer even better, I am going to add buttons.

Let us define a Button module in the same file as our Timer, right above the make function.

1module Button = {
2 [@react.component]
3 let make = (~label, ~onClick) => {
4 <button onClick> {label |> ReasonReact.string} </button>;
5 };

This button takes a label and an onClick prop. We can add them to our Timer, at the bottom of the make function like so:

2let make = () => {
3 /* useReducer */
5 /* useEffect0 */
7 <div>
8 {ReasonReact.string(
9 "There are " ++ string_of_int(state.seconds) ++ " seconds on the clock",
10 )}
11 {state.isTicking
12 ? <Button label="STOP" onClick={_event => dispatch(Stop)} />
13 : <>
14 <Button label="START" onClick={_event => dispatch(Start)} />
15 <Button label="RESET" onClick={_event => dispatch(Reset)} />
16 </>}
17 </div>;

Try running this in your browser, you should see:

start and stop buttons

If you click START, it will start. If you click STOP it will stop. RESET will bring the timer back up to the initial time. Pretty straightforward how it just works!

At this point, our app is feature-complete. Read on to make it even cooler, with style and other aesthetic details.

Aesthetic Concerns

Let us add some styles and make this timer look pretty. Or at least better.

Update the JSX in Timer to the following:

2let make = () => {
3 /* useReducer */
5 /* useEffect0 */
7 style={ReactDOMRe.Style.make(
8 ~border="1px solid black",
9 ~borderRadius="8px",
10 ~maxWidth="180px",
11 ~textAlign="center",
12 (),
13 )}>
14 <p
15 style={ReactDOMRe.Style.make(
16 ~color="#444444",
17 ~fontSize="42px",
18 ~margin="16px 0",
19 (),
20 )}>
21 {state.seconds |> formatTime |> str}
22 </p>
23 {state.isTicking
24 ? <Button label="STOP" onClick={_event => dispatch(Stop)} />
25 : <>
26 <Button label="START" onClick={_event => dispatch(Start)} />
27 <Button label="RESET" onClick={_event => dispatch(Reset)} />
28 </>}
29 </div>;

I have introduced the default styles that come with ReasonReact. They are not my preferred style solution as I like bs-css better, but for this small project, they will do fine.

I also introduce a formatTime function. Let us implement that function so our project compiles:

1let padNumber = numString =>
2 if (numString |> int_of_string < 10) {
3 "0" ++ numString;
4 } else {
5 numString;
6 };
8let formatTime = seconds => {
9 let mins = seconds / 60;
10 let minsString = mins |> string_of_int |> padNumber;
11 let seconds = seconds mod 60;
12 let secondsString = seconds |> string_of_int |> padNumber;
13 minsString ++ ":" ++ secondsString;

I included padNumber as well, a useful utility that pads minutes and seconds which are less than 10. This makes the timer more reader friendly.

I will be honest, this timer looks pretty good right now and I have not even styled the buttons. I will leave that as a task for the reader if they are so inclined.

finished timer

Update the Document Title

The concept of a timer in the browser can be further improved. If we have the time remaining persist in the browser tab itself, it would be visible if the user is in another tab.

All we have to do to get that going is update our Tick action in the reducer. I’ll even show off ReasonML’s interop with JavaScript by updating the document title. Note the %bs.raw directive, this allows us to put on the JavaScript training wheels and use it directly.

1let updateTitle: string => unit = [%bs.raw
2 {|
3 function updateTitle(remaining) {
4 document.title = "⏰ " + remaining + " ⏰";
5 }|}
9let make = () => {
10let (state, dispatch) =
11 React.useReducer(
12 (state, action) =>
13 switch (action) {
14 | Start => {...state, isTicking: true}
15 | Stop => {...state, isTicking: false}
16 | Reset => {...state, seconds: 30}
17 | Tick =>
18 state.isTicking && state.seconds > 0
19 ? {
20 updateTitle(formatTime(state.seconds - 1));
21 {...state, seconds: state.seconds - 1};
22 }
23 : state
24 },
25 {isTicking: false, seconds: 30},
26 );
28/* useEffect0 */
31/* JSX return */

And with that, I am finished with the implementation of the timer:

finished timer with title update


With this tutorial we tackled the updated ReasonReact syntax with React hooks. when React hooks dropped late last year I could not wait to be able to use them in Reason projects. Now that they are here, we can take advantage of strong typed, composable, functional code.

We learned:

  • how to make a basic stateless component
  • how to use the useReducer hook
  • how to use the useEffect hook
  • how to define other React components in the same file/module.
  • how to use basic styles in ReasonReact
  • how to do interon with %bs.raw

I hope this has been a fun or useful experience, be sure to follow me @iwilsonq on dev.to, Twitter, Medium or anywhere else I roam.

If you want to how ReasonML works seamlessly with GraphQL, check out this article I wrote on ReasonML with GraphQL, the Future of Type-Safe Web Applications.

If you’d like to keep up with future posts, sign up for my newsletter here!

More articles from Narative

The Edge, Wit, and Courage of ReasonML

Discover the features of Reason that make it so appealing to a JavaScript developer.

March 19th, 2019 · 4 min read

Intro to ReasonML Variants

Learn to wield ReasonML variants to create better, typesafe web applications

March 2nd, 2019 · 3 min read
© 2019 Narative
Link to $https://twitter.com/iwilsonqLink to $https://github.com/iwilsonqLink to $https://instagram.com/iwilsonqLink to $https://www.linkedin.com/iwilsonq/