Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Modeling Time in React

DZone's Guide to

Modeling Time in React

Have you ever wanted to build a timer in React? It’s a tricky thing to do. Let me show you how it can be done successfully.

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

Ever wanted to build a timer in React? It’s a tricky thing.

Ideally, React components rely only on their inputs – the props – so that they’re testable, reusable, and easier to understand. Time is the ultimate state. That global dependency that just won’t sit still.

Calling new Date() or moment() to get the current time in your component makes it dirty. You can’t test because it throws unpredictable results depending on system context. You can’t reuse and re-render either. Damn thing keeps changing!

You also need some mechanism to keep refreshing that time state if you want your component to show something live. You can add a setInterval that runs this.setState(moment()) every second, and that’s going to work. However, if you show multiple timers on screen, they’re eventually going to diverge and look weird.

Crib From System and Hardware Design

Those problems have all been solved already in electronics and operating systems: it’s the clock signal in electronics and system time in operating systems. Both reduce time to a stateful resource that everyone shares.

The idea is this:

  • Make a Clock store.
  • Emit an action every period milliseconds.
  • Share Clock with everyone.

With this approach, time becomes just another prop passed or injected into components that need it. Components themselves can treat it like an immutable value, which makes them easy to test, and because all components rely on the same setInterval, they’re never going to fall out of sync.

Let me show you.

I’m going to use MobX, but the same approach should work with Redux and even the classical state-from-main-component-callbacks-up-components approach.

You can see the code on GitHub.

Clock Store

First, we need a Clock store. It looks like this:

import { observable, action } from 'mobx';
import moment from 'moment';

class Clock {
    @observable time = moment();

    constructor(period = 1000) {
        this.interval = setInterval(() => this.clockTick(),
                                    period);
    }

    @action clockTick(newTime = moment()) {
        this.time = newTime;
    }
}

const clock = new Clock();

export default clock;

We have an @observabletime property, which means MobX is going to communicate changes to any observers. The constructor starts an interval with the specified period. In our case, this is going to be a 1Hz clock updating once per second.

We store the interval in this.interval so that we can stop it. This implementation doesn’t allow the clock to be stopped or reset, but it would be easy to add an action for that.

Each tick of the clock triggers an @action called clockTick, which updates the time property to the current time. MobX is smart enough to let us naively replace it with a new instance of moment(), and I’m sure Redux would be too.

The real trick to making this work is in the last two lines:

const clock = new Clock();

export default clock;

We export an instance of Clock, not the class. This ensures that anywhere we use import Clock, we get the same singleton.

“But inject()! You can inject() and that will make a singleton!” I hear you thinking.

Yes, but you can only inject() into React components. Sometimes MobX stores need access to The Clock as well. You can’t inject into those, but you can import stuff.

Time Display

Clock was the fun part. Let me show you that it’s easy to use

We make a Time* component that displays durations. It can be a functional stateless component that takes Clock from React contexts via inject() and renders a thing.

const CurrentTime = inject('Clock')(observer(({ Clock }) => (
    <div>
        Current Time: <Duration d={Clock.time} />
    </div>
)));

It observes changes on the Clock state and gets Clock from the context with inject. You could inject a static object with a time = N property when testing.

The Duration component takes a moment() object and displays it as a digital clock. Like this:

const Duration = ({ d }) =&gt; {
    let h = d.hours(),
        m = d.minutes(),
        s = d.seconds();

    [h, m, s] = [h, m, s].map(n =&gt; n &lt; 10 ? `0${n}` : n);

    return <code>{h}:{m}:{s}</code>;
};

Take hours/minutes/seconds from the object, and prefix with a 0when each is smaller than 10. Yes, this breaks for negative values. It looks like this: 0-1:0-4:05.

But that shouldn’t be hard to fix

In the full code, I built a generalized Time displays that defers to TimeSince, TimeUntil, and CurrentTime as necessary. Their code is almost identical, so I didn’t want to explain it all here.

Putting It Together in App.js

Now that you have a system Clock and a way to show Time, you can put it all together inside your App like this:

class App extends Component {
  render() {
      return (
          <Provider Clock={Clock}>
              <div className="App">
                  <DevTools />
                  <div className="App-intro">
                      <Time until={moment().add(10, 'minutes')} />
                      <Time since={moment().subtract(5, 'minutes')} />
                      <Time />
                  </div>
              </div>
          </Provider>
    );
  }
}

Provider puts the Clock singleton in React context. This gives all your components access to the Clock via inject() and you can do anything you want with it.

Cool, isn’t it?

And yes, it works in stores, too.

Check this out from my Day Job code.

View image on Twitter

It’s in a store, isOutOfTime is a @computed property that compares Clock.time to some pre-defined deadline. when() the deadline passes, an @action is called.

    @computed get timeLeft() {
        if (this.should_end_by) {
            return moment.duration(
                this.should_end_by
                                  .diff(Clock.time)
                          );
        }else{
            return null;
        }
    }

    @computed get isOutOfTime() {
        return !_.isNull(this.timeLeft) &amp;&amp; this.timeLeft &lt;= 0;
    }

Isn’t that cool? I think it’s cool. The code is easy to understand, it's easy to test, and there's no messing around with intervals and relying on slippery system properties. Things just work.

It’s almost like your codebase is in a time monad!

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:
react ,web dev ,timers

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}