CodeBlanks Logo Icon CodeBlanks

Increment and decrement

Add increment and decrement buttons.

Increment and decrement functions

To change the counter we will define two functions: increment adds one to the number, decrement subtracts one. These functions call setCount.

Example: function increment() { setCount(count + 1); }. Here count + 1 is passed as the new value to setCount.

We define the functions inside the App component, before return. This way they can access count and setCount.

Function definition

Defining a function inside the component lets it access count and setCount. This comes from React's closure behavior.

Definitions: function increment() { setCount(count + 1); } and function decrement() { setCount(count - 1); }.

We are not calling these functions yet; in the next lesson we will wire them to buttons. For now we just add the definitions.

Practice Add the functions

Add the increment and decrement functions to the existing App component. increment calls setCount(count + 1), decrement calls setCount(count - 1). Define the functions before return.

Starter code

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

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <View>
      <Text>Counter: {count}</Text>
    </View>
  );
}

Sample solution

App.js
import { View, Text } 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>
    </View>
  );
}

Questions and answers

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

1 Match the functions

Term Meaning
increment Adds one
decrement Subtracts one
setCount Setter
count + 1 Increment amount

2 increment body

Question
function increment() {
  ____;
}
Answer
function increment() {
  setCount(count + 1);
}

Explanation: setCount(count + 1) increases the number by one.

3 What should the decrement function do?

  • setCount(count + 1)
  • decrement(count)
  • count - 1
  • setCount(count - 1) Correct answer

Explanation: decrement subtracts one from the number.

All lessons in Beginner