DEV Community

Scott Price
Scott Price

Posted on

Looking for feedback - A React component that will function as a "heartbeat", or timer, for an application.

I have never seen React used like this before so I am curious what other developers will think about it.

Here is the gist: https://gist.github.com/sayes2x/72d884c415662701e38c08b0d696c768

This component is a React implementation of 'accurate interval' developed by @Squeegy which can be found here: https://gist.github.com/Squeegy/1d99b3cd81d610ac7351. Here is how Squeegy's function works: after each setTimeout call, a function compares when setTimeout was called with when setTimeout should have been called. The next call to setTimeout is adjusted to keep it as close as possible to the desired interval.

This component accepts two props:

  1. heartbeatInterval: provides an interval in milliseconds, The Heartbeat component will call a function repeatedly at this timer interval as long as it is rendered. The default value for this interval is 1000 milliseconds.
  2. heartbeatFunction: a function that will be called every time the heartbeatInterval expires.

This component does not render anything, all the render function returns is a Fragment. The only thing this component does is call a function in a parent component at the set interval.

Here is how I use it:

  1. In the parent component I have a state that is a boolean, in this case the state is called paused:
this.state = {
  paused: true
}
  1. In the render function of the parent component, before the return, I have a ternary operator that sets a variable to null if paused is true and sets the variable to the Heartbeat component if paused is false. In this case I used the default value of 1000 milliseconds for the heartbeatInterval prop:
const timer = this.state.paused === true ? 
  null : 
  <Heartbeat heartbeatFunction={this.countdown} />;
  1. In the return part of the render function of the parent component I render the variable defined in step 2, along with whatever else I want this component to render:
return (
  <Fragment>
  {timer}
  <OtherComponents or HTML tags />
  </Fragment>
)

I like this implementation because all I have to do is change a boolean in the state of my component to turn the timer on or off. Since I have not seen a Componant implemented in this way before, I am looking for feedback from other developers.

To see this componenant used in a project go to https://github.com/sayes2x/pomodoro-clock/tree/master/src/components
This component is in the heartBeat.js file and it is used in the timer.js file

Top comments (0)