Signup/Sign In

What is State in React Native?

Posted in Programming   LAST UPDATED: NOVEMBER 11, 2021

    The state in react native is a property of a component that can be changed when an event occurs.

    In react native, there are two types of things that control components; props and state. The props are set only once while creating a component but for the data that may change, based on the user experience, we have to use state.

    State in React Native

    Let's understand this using an example, a button that is used to change the theme or background of an app into a dark or a light mode changes the state of style. Whenever we press that button, it changes the state to its opposite, if the light mode is active then clicking on the button will change the mode to dark mode.

    The state is a mutable thing that can be changed whenever required and we use the constructor to initialize the state and whenever we need to update it we use the built-in function setState to make changes to it.

    Remember, whenever we change a state react-native automatically reloads all the components. So we don't have to reload the components by ourselves.

    Also Read: What is React Native?

    Let's understand the state using a working example.

    In this example, we have built an app that has a login button and whenever we click on that button, it automatically changes the background of the app. And for this, we are going to use the random() function to generate a new RGB value every time when the button is clicked.

    import React from 'react';
    import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
    export default class App extends React.Component{ 
     constructor(){
       super();
       this.state = {
         randomColor: null
       };
     }
    getRandomColor = () => {
      return(
        "rgb(" +
        Math.floor((Math.random() * 256)) +
        "," +
        Math.floor((Math.random() * 256)) +
        "," +
        Math.floor((Math.random() * 256)) +
        ")"
      )
    }
     myButtonPressed = () => {
       this.setState({randomColor: this.getRandomColor()})
     }
      render(){
        return(
          <View style={[styles.container, {backgroundColor: this.state.randomColor}]}>
            <TouchableOpacity onPress={this.myButtonPressed}>
            <Text style={styles.text}>Login</Text>
            </TouchableOpacity>
          </View>
    
        );
      }
    }
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
      text: {
        fontSize: 30,
        backgroundColor: "#BB2CD9",
        paddingHorizontal: 40,
        paddingVertical: 10,
        color: "#FFFFFF",
        borderRadius: 10,
        borderWidth: 2,
        borderColor: "#FFFFFF"
      }
    });

    Output:

    In the images below you can see how the color changes.

    state in react native state in react native

    Code Explanation:

    In the code above, first, we imported the StyleSheet, Text, View, TouchableOpacity that we are going to use in this program. TouchableOpacity is a built-in component that is used to set the onPress() method on another component that is not clickable. In the above code, we have set the onPress() method on a Text component using the TouchableOpacity component.

    Next, we defined and exported the class App as a default component, and by using the constructor we defined a variable randomColor using state and assinged null as value for it. The constructor is a method that runs automatically by default whenever we call the class, in this case class App.

    Next, we have defined a method called getRandomColor() that returns a random value of an RGB color using the built-in module Math.

    Next, we defined a method called myButtonPressed() and inside it, we have used the setState() method to set the random value of randomColor variable using the getRandomColor() function.

    Next, in the render() method, we returned a view in which we defined a Text component and on that, we have set the onPress() method that will call the myButtonPressed() function whenever we press on the Login text.

    Using the myButtonPressed() function we update the state or value of the randomColor variable, and whenever we set the new state react-native automatically reloads the component with respect to the current state. Using the style property we set the new value of the background color to the View.

    So, remember we only need to use the state when we want to change any component, and it is necessary that we use the setState() method to change the state of a component.

    Conclusion:

    In this tutorial, we covered what is state in react native and how we can use the state to change various values and hence update the react native components, using the setState() method.

    You may also like:

    About the author:
    Yash Pal is a highly skilled technical author with a passion for writing about React and React Native.His articles are highly informative and filled with practical insights and tips for developers, providing valuable guidance on React Native Language
    Tags:ReactNativeReactNative StateMobile Application
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS