0
0
React Nativemobile~20 mins

useEffect hook in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Timer Screen
This screen shows a timer that counts seconds after the screen loads. It uses the useEffect hook to start and clean up the timer.
Target UI
-------------------
| Timer Screen    |
|-----------------|
| Seconds: 0      |
|                 |
| [Reset Timer]   |
-------------------
Display a seconds counter starting at 0
Use useEffect to start a timer that increments seconds every second
Clean up the timer when the component unmounts
Add a Reset Timer button that sets seconds back to 0
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function TimerScreen() {
  const [seconds, setSeconds] = useState(0);

  // TODO: Use useEffect to start timer and clean up

  return (
    <View style={styles.container}>
      <Text style={styles.timerText}>Seconds: {seconds}</Text>
      <Button title="Reset Timer" onPress={() => setSeconds(0)} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  timerText: {
    fontSize: 32,
    marginBottom: 20,
  },
});
Task 1
Task 2
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function TimerScreen() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.timerText}>Seconds: {seconds}</Text>
      <Button title="Reset Timer" onPress={() => setSeconds(0)} />
    </View>
  );
}

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

We use the useEffect hook to start a timer when the screen loads. The timer uses setInterval to add 1 to the seconds every 1000 milliseconds (1 second). The empty dependency array [] means this effect runs only once when the component mounts. We return a cleanup function that clears the interval when the component unmounts to avoid memory leaks. The Reset button sets the seconds back to 0 immediately.

Final Result
Completed Screen
-------------------
| Timer Screen    |
|-----------------|
| Seconds: 12     |
|                 |
| [Reset Timer]   |
-------------------
Seconds number increases by 1 every second automatically
Pressing Reset Timer sets seconds back to 0 immediately
Stretch Goal
Add a Pause/Resume button to stop and start the timer
💡 Hint
Use a state variable to track if timer is running and conditionally start/stop the interval inside useEffect