How to show current time and update the seconds in real time with React Native?

Sometimes, we want to show current time and update the seconds in real time with React Native.

In this article, we’ll look at how to show current time and update the seconds in real time with React Native.

How to show current time and update the seconds in real time with React Native?

To show current time and update the seconds in real time with React Native, we can use the setInterval function to update the time every second.

For instance, we write:

import * as React from 'react';
import { Text, View } from 'react-native';


export default function App() {
  const [time, setTime] = React.useState();

  React.useEffect(() => {
    const timer = setInterval(() => {
      setTime(new Date().toLocaleString());
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <View>
      <Text>{time}</Text>
    </View>
  );
}

to call setInterval with a callback that calls setTime with new Date().toLocaleString() to set time to the current date time string.

The 2nd argument of setInterval is 1000 so the callback runs every second.

Also, we return a function that calls clearInterval to clear the timer when we unmount the component.

The useEffect hook is called with an empty array so the useEffect callback runs only when App mounts.

Finally, we display the time in the Text component.

Conclusion

To show current time and update the seconds in real time with React Native, we can use the setInterval function to update the time every second.