Lesson 34 of 60 – useState Hook in React Native
57%

useState Hook in React Native

The useState Hook is used to store and manage changing data inside a functional component. It allows a React Native component to remember a value and update the UI when that value changes.

Note: When state changes, React Native re-renders the component so that the updated value can be displayed on the screen.

1. What is useState?

useState is a React Hook that allows functional components to store changing values.

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

Here, count is the current value and setCount is the function used to update it.

2. Why is useState Used?

  • To store changing data.
  • To update information displayed on the screen.
  • To create counters.
  • To manage form input values.
  • To control buttons and UI states.
  • To manage selected items.
  • To create interactive applications.

3. Importing useState

Before using useState, import it from React.

import React, {
    useState
} from 'react';

You can then use useState() inside your functional component.

4. Basic useState Syntax

const [value, setValue] = useState(initialValue);

The syntax contains three important parts:

  • value – current state value.
  • setValue – function used to update the state.
  • initialValue – starting value.

5. Creating a Number State

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

The initial value of count is 0.

You can later update it using setCount().

6. Updating State

Use the state setter function to update the state.

setCount(10);

After this update, the value of count becomes 10.

7. useState with Button

import React, {
    useState
} from 'react';

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

export default function App() {

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

    return (

        <View>

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

            <Button
                title="Increase"
                onPress={() =>
                    setCount(count + 1)
                }
            />

        </View>

    );

}

8. Incrementing a State Value

setCount(count + 1);

This increases the current value by one.

For example:

0 → 1 → 2 → 3 → 4

9. Decrementing a State Value

setCount(count - 1);

This decreases the current state value by one.

5 → 4 → 3 → 2 → 1

10. Boolean State

State can also store true or false.

const [isVisible, setIsVisible] =
    useState(true);

Boolean state is useful for showing and hiding UI elements.

11. Toggling Boolean State

setIsVisible(!isVisible);

This changes:

true → false
false → true

It is commonly used for toggles, menus and visibility controls.

12. String State

const [name, setName] =
    useState('Rahul');

The state starts with the string Rahul.

It can later be changed:

setName('Amit');

13. useState with TextInput

One of the most common uses of useState is storing the value entered into a TextInput.

const [name, setName] =
    useState('');

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Enter your name"
/>

14. Displaying State on Screen

const [name, setName] =
    useState('Rahul');

<Text>
    Hello {name}
</Text>

When the state changes, the displayed text also updates.

15. Multiple State Variables

A component can have multiple state variables.

const [name, setName] =
    useState('');

const [age, setAge] =
    useState(18);

const [isActive, setIsActive] =
    useState(true);

Each state variable has its own setter function.

16. State with Objects

State can store an object containing multiple related values.

const [student, setStudent] =
    useState({
        name: 'Rahul',
        age: 20,
        course: 'React Native'
    });

17. Updating Object State

When updating an object, keep the existing properties using the spread operator.

setStudent({
    ...student,
    age: 21
});

This updates only the age property while preserving the other properties.

18. State with Arrays

const [students, setStudents] =
    useState([
        'Rahul',
        'Amit',
        'Priya'
    ]);

An array state is useful when working with lists of data.

19. Adding an Item to Array State

setStudents([
    ...students,
    'Neha'
]);

The spread operator keeps the existing items and adds the new item.

20. Functional State Update

When a new state value depends on the previous value, a functional state update is often preferred.

setCount(
    previousCount =>
        previousCount + 1
);

This tells React to calculate the new value from the previous state.

21. useState and Re-rendering

When the state setter updates a value, React schedules the component to render again with the updated state.

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

setCount(1);

The UI can then display the new value.

22. Showing and Hiding Components

const [showMessage, setShowMessage] =
    useState(false);

{showMessage && (

    <Text>
        Welcome to React Native!
    </Text>

)}

The message is displayed only when showMessage is true.

23. useState with Pressable

const [liked, setLiked] =
    useState(false);

<Pressable
    onPress={() =>
        setLiked(!liked)
    }
>

    <Text>
        {liked ? '❤️ Liked' : '♡ Like'}
    </Text>

</Pressable>

This creates a simple interactive like button.

24. useState with Login UI

const [email, setEmail] =
    useState('');

const [password, setPassword] =
    useState('');

<TextInput
    value={email}
    onChangeText={setEmail}
    placeholder="Email"
/>

<TextInput
    value={password}
    onChangeText={setPassword}
    placeholder="Password"
    secureTextEntry
/>

Each input has its own state value.

25. useState with Loading State

const [loading, setLoading] =
    useState(false);

const handleLogin = () => {

    setLoading(true);

    // Perform operation

};

A boolean state can be used to control a loading indicator or disable a button while an operation is running.

26. Common useState Mistakes

  • Forgetting to import useState.
  • Calling useState outside a component.
  • Changing the state variable directly.
  • Using the wrong setter function.
  • Ignoring the previous state when an update depends on it.
  • Mutating arrays or objects directly.
  • Creating unnecessary state variables.
  • Using state when a normal constant would be enough.

For example, avoid directly changing an array:

students.push('Neha');

Instead, create a new array:

setStudents([
    ...students,
    'Neha'
]);

27. Complete Counter Example

import React, {
    useState
} from 'react';

import {
    View,
    Text,
    Button,
    StyleSheet
} from 'react-native';

export default function App() {

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

    return (

        <View style={styles.container}>

            <Text style={styles.title}>
                Counter
            </Text>

            <Text style={styles.count}>
                {count}
            </Text>

            <Button
                title="Increase"
                onPress={() =>
                    setCount(
                        previousCount =>
                            previousCount + 1
                    )
                }
            />

            <View
                style={styles.space}
            />

            <Button
                title="Decrease"
                onPress={() =>
                    setCount(
                        previousCount =>
                            previousCount - 1
                    )
                }
            />

        </View>

    );

}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20
    },

    title: {
        fontSize: 28,
        fontWeight: 'bold',
        marginBottom: 20
    },

    count: {
        fontSize: 40,
        fontWeight: 'bold',
        marginBottom: 20
    },

    space: {
        height: 10
    }

});

28. useState Best Practices

  • Use meaningful state names.
  • Keep state as simple as possible.
  • Use the setter function to update state.
  • Use functional updates when the new value depends on the previous value.
  • Do not directly mutate objects or arrays.
  • Keep related state together when appropriate.
  • Avoid storing values that can be calculated from existing state.
  • Use boolean state for simple UI conditions.
  • Keep state close to the component that needs it.

29. useState vs Normal Variable

useState Normal Variable
Stores component state Stores a temporary JavaScript value
Updating state can cause re-rendering Changing a normal variable does not trigger a React render
State value is preserved between renders Normal local variables are recreated during rendering
Uses a setter function Can be assigned directly

30. Complete useState Workflow

Import useState
        ↓
Create Functional Component
        ↓
Declare State
        ↓
Set Initial Value
        ↓
Display State
        ↓
Create User Interaction
        ↓
Call State Setter
        ↓
React Updates State
        ↓
Component Re-renders
        ↓
Updated UI is Displayed

The useState Hook is fundamental for creating interactive React Native applications. It can be used for counters, forms, buttons, visibility controls, loading states, selections and many other dynamic UI requirements.

📌 Key Points

  • useState is used to manage changing data.
  • It is commonly used inside functional components.
  • The syntax is const [value, setValue] = useState(initialValue).
  • The first value represents the current state.
  • The second value is the state setter function.
  • State can contain numbers, strings, booleans, arrays and objects.
  • Use the setter function instead of changing state directly.
  • Use functional updates when the new value depends on the previous value.
  • State changes can cause the component UI to update.
  • useState is essential for building interactive React Native applications.

🧠 Quick Quiz

Question: Which Hook is used to manage state in a functional React Native component?