How to use State in React Native?

May 16, 2022 . Admin

Hi Guys,

This article will provide some of the most important example state example in react native. I would like to share with you how to use state in a functional component in react native. if you have a question about react native state example then I will give a simple example with a solution. I’m going to show you about how to use state in react native. Let's get started with how to implement state in react native.

state is like a component’s personal data storage. The state is useful for handling data that changes over time or that comes from user interaction. State gives your components memory!

You can add state to a component by calling React’s useState Hook. A Hook is a kind of function that lets you “hook into” React features. For example, useState is a Hook that lets you add state to function components.

Step 1: Download Project

In the first step run the following command to create a project.

expo init StateDemo
Step 2: App.js

In this step, You will open the App.js file and put the code.

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

const App = () => {
    const [value, setValue] = useState('Divyesh');

    const addChange = () => {
        setValue('Bhavesh');
    }

    const reset = () => {
        setValue('Divyesh');
    }

    return (
        <View style={styles.container}>
            <Text style={styles.text}>Welcome {value} !</Text>
            <View style={styles.buttonView}>
                <View style={styles.button}>
                    <Button 
                        title='change'
                        onPress={() => addChange()}
                    />
                </View>
                <View >
                    <Button 
                        title='Reset'
                        onPress={() => reset()}
                    />
                </View>
            </View>
            <StatusBar backgroundColor={'blue'}/>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        justifyContent:'center',
        alignItems:'center',
    },
    text: {
        fontSize:28,
        fontWeight:'bold',
    },
    buttonView: {
        marginTop:15,
        flexDirection:'row',
    },
    button: {
        marginRight:10,
    },
});

export default App;
Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...

#React Native