Timer mixin

Published in Others
May 06, 2023
1 min read
Timer mixin

Introduction

Using bare setTimeout, setInterval, setImmediate and requestAnimationFrame calls is very dangerous because if you forget to cancel the request before the component is unmounted, you risk the callback throwing an exception.

If you include TimerMixin, then you can replace your calls to setTimeout(fn, 500) with this.setTimeout(fn, 500) (just prepend this.) and everything will be properly cleaned up for you.

Installation

npm install react-timer-mixin

Example

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import TimerMixin from 'react-timer-mixin';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      countdown: 10, // set the initial countdown time in seconds
    };
  }

  componentDidMount() {
    this.timer = TimerMixin.setInterval(() => {
      if (this.state.countdown === 0) {
        TimerMixin.clearInterval(this.timer);
        return;
      }

      this.setState((prevState) => ({
        countdown: prevState.countdown - 1,
      }));
    }, 1000);
  }

  componentWillUnmount() {
    TimerMixin.clearInterval(this.timer);
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.timerText}>{this.state.countdown}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  timerText: {
    fontSize: 48,
  },
});

Tutorial

Coming Soon…


Previous Article
Vertical Step indicator
Next Article
Swiper Animated
Awesome React Native
© 2024, All Rights Reserved.

Social Media