CodeBlanks Logo Icon CodeBlanks

Putting it together

Combine all parts into a working counter.

Combining and reset

Our counter app is almost done. The increment and decrement buttons now work. We will now add a reset feature; this sets the number back to zero.

The reset function also calls setCount: function reset() { setCount(0); }. This returns the number to its initial value.

Finally we will add a third <TouchableOpacity> button and wire it with onPress={reset}. This will complete the app.

Reset button

After defining the reset function, we wire it to a <TouchableOpacity> button too. This lets the user reset the counter.

Button: <TouchableOpacity onPress={reset}><Text>Reset</Text></TouchableOpacity>.

We add this below the other two buttons. This way we have a three-button, working counter app.

Practice Add reset

Add a reset function to the existing App: function reset() { setCount(0); }. Add a third <TouchableOpacity onPress={reset}> button containing <Text>Reset</Text>. Place the button below the others.

Starter code

App.js
import { View, Text, TouchableOpacity } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  function increment() {
    setCount(count + 1);
  }

  function decrement() {
    setCount(count - 1);
  }

  return (
    <View>
      <Text>Counter: {count}</Text>
      <TouchableOpacity onPress={increment}>
        <Text>Increase</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={decrement}>
        <Text>Decrease</Text>
      </TouchableOpacity>
    </View>
  );
}

Sample solution

App.js
import { View, Text, TouchableOpacity } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  function increment() {
    setCount(count + 1);
  }

  function decrement() {
    setCount(count - 1);
  }

  function reset() {
    setCount(0);
  }

  return (
    <View>
      <Text>Counter: {count}</Text>
      <TouchableOpacity onPress={increment}>
        <Text>Increase</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={decrement}>
        <Text>Decrease</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={reset}>
        <Text>Reset</Text>
      </TouchableOpacity>
    </View>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the whole app

Term Meaning
useState State
increment Increase
decrement Decrease
reset Reset

2 reset body

Question
function reset() {
  ____;
}
Answer
function reset() {
  setCount(0);
}

Explanation: setCount(0) sets the number to zero.

3 What does the reset button do?

  • Increases the number by one
  • Sets the number to zero Correct answer
  • Decreases the number by one
  • Hides the number

Explanation: reset sets the number to zero.

All lessons in Beginner