Updated March 27, 2023
Introduction to React Native State
State is the main attribute of react native which is mutable in nature(which means its values can be changed inside the component), it gives a powerful mechanism to manage the data available inside any component from start to end of the component life cycle (state is object containing all the data required to create component combining with HTML), in case of any change in the state render function get executed (which means if some change happens to textbox then state change happens and render function get called to show the required changes), in general, all the state get initialize inside the constructor function.
Syntax:
In the below state syntax, we are initializing the value for the state on initialization and once anyone will click on the div with the text “click me to change the state” then the state will change and new changed value of data1,data2,data3 will be set.
class stateSyntax extends Component {
constructor(props: Props) {
super(props);
this.state = {
data1: 0, //may be initialization of cart items
data2: 0, //may be initialisation of initial price for the total cart value
data3: null, //may be initialisation for the any coupon
};
}
handlerFunction = () => {
this.setState({data1:2})
this.setState({data2:200})
this.setState({data3:20})
}
render() {
return (
//on first time loading of the component constructor initialized state value will be visible
<View>
<div>this.state.data1</div>
<div>this.state.data2</div>
<div>this.state..data3</div>
</View>
<div onPress={this.handlerFunction}>
Click me to change the state
</div>
);
}
}
How does React Native State work?
Working of react native is very simple, we can define the working principle of state in react native in the below steps:
- As we know the state in the react-native is the object, so this state will be initialized inside the constructor function.
- On the loading of any component first, it will check for the initialized value.
- With the help of this keyword, we can access the value of any state data, like console.log(state.data)
- If there will be any change in any attribute of the state data then render function will be executed. For example, if in the initial value of username attribute of the state object is “ranjan” and anyone will change it from “ranjan” to “ajay” like this.setState({username:”ajay”}) then render function will be executed. One can see the changes.
Examples of React Native State
Given below are the examples of React Native State:
Example #1
This is a very basic example of a react-native state, here we are simply initializing state with “myCustomeMsg” attribute and on clicking on the text we are calling a function called “updateCustomeMsg”, this function will update message. As we know that in react native if any change happens in the value of the state the render function will get called and the changed value which is bind with ui and states will be visible on the app. Please follow the below example with two screens of output, in the first image message was what we set in the initialization part and in the next image changed message after a click.
Code:
import React, { Component } from "react";
import { Text, View } from "react-native";
export default class stateExample extends Component {
state = {
myCustomeMsg:
"This the initialisation of the state myCustomeMsg , onclicking on me i will change as state value will get change"
};//initialisation of the state value
updateCustomeMsg = () =>
this.setState({ myCustomeMsg: "Initial message changed here" });
render() {
return (
<View>
<Text onPress={this.updateCustomeMsg}> {this.state.myCustomeMsg} </Text>
</View>
);
}
}
Output:
Example #2
In the below example we are creating a class state example which is extending the react core library. Inside the function state example, we are initializing three state values “userPass”,”isVisible” and “toggleMsg”. The attribute “isVisible” will get changed on click show and hide text. Please see the example output screen for the code. In the images initially, there was “show” text with blank box, in the next image we can see the text message “welcome” inside the text box because we clicked “show” text, but in the 3rd image “welcome” image is not visible to us as we clicked “hide” text. All these events are happening because initially “isVisible” was true(state initialized inside the constructor) and when we clicked “hide” text “isVisible” became false.
Code:
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity
} from "react-native";
export default class stateExample extends Component {
constructor(props) {
super(props);
this.state = {
userPass: "",
isVisible: true,
toggleMsg: "Show"
};
}//here we are initialising the value of state attributes.
handleClick = () => {
const { isVisible } = this.state;
if (isVisible) {
this.setState({ isVisible: false });
this.setState({ toggleMsg: "Hide" });
} else {
this.setState({ isVisible: true });
this.setState({ toggleMsg: "Show" });
}
};
render() {
return (
<View style={stateStyles.containerStyle}>
<TextInput
secureTextEntry={this.state.isVisible}
style={{
width: 411,
height: 53,
backgroundColor: "green",
color: "white",
fontSize: 21
}}
/>
<TouchableOpacity onPress={this.handleClick}>
<Text style={{ fontSize: 21 }}>{this.state.toggleMsg}</Text>
</TouchableOpacity>
</View>
);
}
}
const stateStyles = StyleSheet.create({
containerStyle: {
flex: 1,
justifyContent: "start",
alignItems: "start"
}
});
Output:
Advantages of using React Native State
- States are like global variables for any component so they are available everywhere inside the given components which can be used for many purposes.
- Because the state is managed by react itself, they take care of memory management very well in this case.
- It will be easy to manage changes and different states of apps with the help of states.
- The state is also a private for its component and can be a mutable inside component. Because it is private inside component states are secure inside any components.
- In case of any parent component sent to the child components then the child component can not change it(props are immutable which means parent states value can not change in child component). With this integrity of the state of any component will be maintained in any child component.
- Easy to manage variables inside states, many components can have the same variable name without any conflict.
Conclusion
From this article we learned about the react-native state, we learned that we can initialize the state of any component and can be available for any life cycle of a given component, we can change the value of state at any particular life cycle and that change will be available for other life cycles.
Recommended Articles
This is a guide to React Native State. Here we discuss the introduction, syntax, and working of React Native State along with examples and code implementation. You may also have a look at the following articles to learn more –