techStackGuru

React native app state


State is a powerful tool in React Native. It helps us understand how the data of our application changes over time and build components that respond to these changes. State has important applications to our user interface because it allows us to represent and maintain these changes. But what exactly is the state?

React state is the perfect solution for managing your state for React applications. React state is a JavaScript object that holds the current values for all of the components local variables and properties. Its often used to keep track of the components internal state.

Example

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

export default class App extends Component {  
  state = {  
    newStates: 'Hello from State'  
  }

changeState = () => this.setState({newStates: 'The state has changed'})  
  render() {    
  return (
    <View style={styles.container}>
        <Text> {this.state.newStates} </Text>  
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  },
});
Output
react-native-hello-world

However, what if we want to update a child element without necessarily altering the value of this.state ? We can do that using an alias called this.setState(). In essence, we are telling React that we are going to alter the state for a particular key and that it will maintain the previous state in case there is one. Finally, we pass an object that has a function to update the value of this.state. This is essentially how setState() works.


Updating the State

import React, {Component} from 'react';  
import { StyleSheet, Text, View } from 'react-native';
 
export default class App extends Component {  
  state = {  
    newStates: 'Click me :)'  
}

changeState = () => this.setState({newStates: 'The state has changed'})  

render() {    
    return (
        <View style={styles.container}>
        <Text style={styles.setFontSize } onPress={this.changeState} > {this.state.newStates} </Text>  
        </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  },
});
Output
react-native-hello-world

previous-button
next-button