Click Counter Basics

Introduction: Tracking User Actions in Mobile Apps

Welcome to the second lesson of the "Introduction to Props and Event Handlers in React Native" course! In our previous lesson, we explored the basics of props — how to pass data from parent to child components to create flexible and reusable UIs. Now, we’re shifting our focus from static data to dynamic user interaction.

In real-world mobile apps, responding to user actions is essential. Whether it’s counting likes, tracking steps, or updating notifications, apps need to react to what users do. In this lesson, you’ll learn how to track and respond to user actions by building a simple click counter. This will introduce you to the concepts of state and event handling in React Native, which are foundational for creating interactive mobile experiences.

Understanding State in React Native

Before we dive into building our click counter, let’s talk about state. In React Native, state is a way for a component to remember information between renders. Unlike props, which are passed in from a parent, state is managed within the component itself.

For example, if you want a button to keep track of how many times it’s been pressed, you need a place to store that number. That’s where state comes in. When the state changes, React Native automatically updates the UI to reflect the new value.

This is different from what you learned about props in the previous lesson. Props are for passing data into a component, while state is for data that changes inside a component.

Using the useState Hook

To manage state in a functional component, React Native provides the useState hook. This hook lets you declare a state variable and a function to update it.

Here’s a minimal example of how to use useState to track a count:

TypeScript
import React, { useState } from "react";
import { Text } from "react-native";

const ClickCounter = () => {
  const [count, setCount] = useState(0);

  return <Text>Count: {count}</Text>;
};

In this example, useState(0) creates a state variable called count and a function called setCount to update it. The initial value is 0. Every time setCount is called, the component re-renders with the new value of count.

This is the foundation for making your app respond to user actions.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal