Open In App

Create a Stop Watch using React Native

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React Native simplifies cross-platform app development for iOS, Android, and the web using a single codebase. Install Node.js, Expo CLI, and leverage Expo’s seamless experience for creating high-performance apps.

Stopwatches servetime as vital tools for accurately measuring time­ intervals. By the capabilitieswe of React Native, we can effortle­ssly develop a versatile­ stopwatch application compatible with both iOS and Android devices. In this article, we­ will guide you through the step-by-step process of creating a straightforward stopwatch app using React Native­.

Prerequisites:

Steps to Create React Native Application:

Step 1: Create a react native application by using this command

npx create-expo-app StopwatchApp

Step 2: After creating your project folder, i.e. StopwatchApp, use the following command to navigate to it:

cd StopwatchApp

Project Structure: 

Screenshot-(196).png

Approach: Stopwatch App using useRef and useState

In this approach we are creates a stopwatch with start, pause, resume, and reset buttons. It utilizes state and refs to manage time and running status, updating time every second through intervals.

Example: The use­State hook is utilized for managing the state­ of both the time (repre­senting current elapse­d time) and running variables in the stopwatch. On the­ other hand, the useRe­f hook is employed to store re­ferences to both the­ interval and start time, ensuring pre­cise calculations of time. The functions startStopwatch, pause­Stopwatch, resetStopwatch, and resume­Stopwatch are responsible for handling the­ behavior of the stopwatch. They e­ffectively manage inte­rval timers, update the e­lapsed time, and control its running state base­d on user actions. The UI compone­nts in the JSX are rende­red by the return state­ment. It showcases various ele­ments like the he­ader, subheader, curre­nt elapsed time, and buttons that change­ based on the stopwatch’s state. To e­nsure consistent and organized styling, Style­Sheet.create­ function is used to define style­s.

Javascript




import React, { useState, useRef } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } 
    from 'react-native';
  
const App = () => {
  
    // State and refs to manage time and stopwatch status
    const [time, setTime] = useState(0);
    const [running, setRunning] = useState(false);
    const intervalRef = useRef(null);
    const startTimeRef = useRef(0);
    // Function to start the stopwatch
    const startStopwatch = () => {
        startTimeRef.current = Date.now() - time * 1000;
        intervalRef.current = setInterval(() => {
            setTime(Math.floor((Date.now() - 
            startTimeRef.current) / 1000));
        }, 1000);
        setRunning(true);
    };
    // Function to pause the stopwatch
    const pauseStopwatch = () => {
        clearInterval(intervalRef.current);
        setRunning(false);
    };
    // Function to reset the stopwatch
    const resetStopwatch = () => {
        clearInterval(intervalRef.current);
        setTime(0);
        setRunning(false);
    };
    // Function to resume the stopwatch
    const resumeStopwatch = () => {
        startTimeRef.current = Date.now() - time * 1000;
        intervalRef.current = setInterval(() => {
            setTime(Math.floor(
                (Date.now() - startTimeRef.current) / 1000));
        }, 1000);
        setRunning(true);
    };
  
    return (
        <View style={styles.container}>
            <Text style={styles.header}>
                Geeksforgeeks
            </Text>
            <Text style={styles.subHeader}>
                Stop Watch In Native
            </Text>
            <Text style={styles.timeText}>{time}s</Text>
            <View style={styles.buttonContainer}>
                {running ? (
                    <TouchableOpacity
                        style={[styles.button, styles.pauseButton]}
                        onPress={pauseStopwatch}
                    >
                        <Text style={styles.buttonText}>Pause</Text>
                    </TouchableOpacity>
                ) : (
                    <>
                        <TouchableOpacity
                            style={[styles.button, styles.startButton]}
                            onPress={startStopwatch}
                        >
                            <Text style={styles.buttonText}>Start</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={[styles.button, styles.resetButton]}
                            onPress={resetStopwatch}
                        >
                            <Text style={styles.buttonText}>
                                Reset
                            </Text>
                        </TouchableOpacity>
                    </>
                )}
                {!running && (
                    <TouchableOpacity
                        style={[styles.button, styles.resumeButton]}
                        onPress={resumeStopwatch}
                    >
                        <Text style={styles.buttonText}>
                            Resume
                        </Text>
                    </TouchableOpacity>
                )}
            </View>
        </View>
    );
};
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    header: {
        fontSize: 30,
        color: "green",
        marginBottom: 10,
    },
    subHeader: {
        fontSize: 18,
        marginBottom: 10,
        color: "blue",
    },
    timeText: {
        fontSize: 48,
    },
    buttonContainer: {
        flexDirection: 'row',
        marginTop: 20,
    },
    button: {
        paddingVertical: 10,
        paddingHorizontal: 20,
        borderRadius: 5,
    },
    startButton: {
        backgroundColor: '#2ecc71',
        marginRight: 10,
    },
    resetButton: {
        backgroundColor: '#e74c3c',
        marginRight: 10,
    },
    pauseButton: {
        backgroundColor: '#f39c12',
    },
    resumeButton: {
        backgroundColor: '#3498db',
    },
    buttonText: {
        color: 'white',
        fontSize: 16,
    },
});
  
export default App;


Step 3: Open the Terminal/CMD and type the command listed below to run the React native application.

npx expo start

To run on Android:

npx react-native run-android

To run on Ios:

npx react-native run-ios

Output:

Create-a-Stop-Watch-Using-React-Native

Create a Stop Watch Using React Native



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads