Thuta Learning
IntermediateMobile Developmentintermediate

State with useState Hook

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand State with useState Hook, no need to be intimidated
  • Write code yourself and run it on Expo Go
  • Apply this concept immediately in a real app project

Let's think about this for a moment

The useState hook is used to track local state within a component — every time the state value changes, it triggers a re-render of the component. React Native imports React's hooks system directly too, so the syntax is exactly the same as web React — the difference lies in UI events (onPress vs onClick) and components (TouchableOpacity vs button).

Let's connect this to a real scenario

To build a like button, you create an isLiked state with useState(false), then call setIsLiked(!isLiked) inside TouchableOpacity's onPress — every press toggles the state and can change the icon color. You'll combine the style conditionally based on state (using the array syntax from the previous lesson).

Code Example

javascript
import { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

export default function LikeButton() {
  const [isLiked, setIsLiked] = useState(false);

  return (
    <TouchableOpacity onPress={() => setIsLiked(!isLiked)}>
      <Text style={[styles.heart, isLiked && styles.liked]}>
        {isLiked ? '❤️' : '🤍'}
      </Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  heart: { fontSize: 32 },
  liked: { transform: [{ scale: 1.2 }] },
});
You should see
Every time you press the heart icon, you'll see it toggle between filled and outline states.

5-Minute Try-It

Build a counter app — create a count state with useState(0) and implement it so count increases every time you press the '+' button.

A Quick Heads-Up

Writing onPress={setIsLiked(!isLiked)} calls the function immediately on every render and can cause an infinite loop — you need to wrap it with an arrow function () => ...

Easy traps

  • Trying to mutate state directly (isLiked = true) — you should always use the setIsLiked function
  • Calling the function immediately inside onPress (onPress={setIsLiked(!isLiked)}) — you need to wrap it in an arrow function (onPress={() => setIsLiked(!isLiked)})

Now Try It Yourself

Build a counter app — create a count state with useState(0) and implement it so count increases every time you press the '+' button.

You'll know it worked when: Every time you press the heart icon, you'll see it toggle between filled and outline states.