0
0
React Nativemobile~5 mins

useState hook in React Native

Choose your learning style9 modes available
Introduction

The useState hook helps you keep track of changing information in your app. It lets your app remember things like user input or button clicks.

You want to remember if a button was clicked to show a message.
You need to store text typed by a user in a form.
You want to toggle between two views, like showing or hiding a menu.
You want to count how many times a user taps a button.
You want to update a part of the screen when something changes.
Syntax
React Native
const [stateVariable, setStateFunction] = useState(initialValue);

stateVariable holds the current value.

setStateFunction is used to change the value and update the screen.

Examples
This creates a number state starting at 0, often used for counters.
React Native
const [count, setCount] = useState(0);
This creates a text state starting empty, useful for input fields.
React Native
const [name, setName] = useState('');
This creates a true/false state to show or hide something.
React Native
const [isVisible, setIsVisible] = useState(true);
Sample App

This simple app shows a number starting at 0. Each time you press the button, the number goes up by 1. The useState hook remembers the number and updates the screen.

React Native
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';

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

  return (
    <View style={{ padding: 20, alignItems: 'center' }}>
      <Text style={{ fontSize: 24, marginBottom: 10 }}>Count: {count}</Text>
      <Button title="Increase" onPress={() => setCount(count + 1)} />
    </View>
  );
}
OutputSuccess
Important Notes

Always use the setter function (like setCount) to change state. Changing the variable directly won't update the screen.

State updates are asynchronous, so the new value appears after React processes the change.

You can use multiple useState hooks to track different pieces of information.

Summary

useState lets your app remember and update values.

Use it to handle user actions like clicks or typing.

Always update state with the setter function to refresh the screen.