DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. JavaScript
  4. Modeling Time in React

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.

Swizec Teller user avatar by
Swizec Teller
·
Nov. 11, 16 · Tutorial
Like (1)
Save
Tweet
Share
2.52K Views

Join the DZone community and get the full member experience.

Join For Free

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!

React (JavaScript library)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Monolithic First
  • Building Microservice in Golang
  • Tracking Software Architecture Decisions
  • Introduction to Spring Cloud Kubernetes

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: