It is used to control the components. The variable data can be stored in the state. It is mutable means a state can change the value at any time.
Example
Here, we are going to create a Text component with state data. The content of the Text component will be updated whenever we click on it. The event onPress calls the setState function, which updates the state with “myState” text.
import React, {Component} from ‘react’;
import { Text, View } from ‘react-native’;
export default class App extends Component {
state = {
myState: ‘This is a text component, created using state data. It will change or updated on clicking it.’
}
updateState = () => this.setState({myState: ‘The state is updated’})
render() {
return (
{this.state.myState}
);
}
}
In React Native, as in React, states are used to manage and store mutable data within a component. States are essentially JavaScript objects that represent the current state of a component and can be updated over time. They allow components to re-render with updated data, providing a dynamic and interactive user interface.
In React Native, you can use the useState
hook to declare and manage states in functional components. Here’s a basic example:
import { View, Text, Button } from ‘react-native’;const MyComponent = () => {
// Declare a state variable named ‘count’ with an initial value of 0
const [count, setCount] = useState(0);
return (
<View>
<Text>{`Count: ${count}`}</Text>
<Button
title=”Increment”
onPress={() => setCount(count + 1)}
/>
</View>
);
};
In this example, the count
state is declared using useState
, and the setCount
function is used to update its value. When the “Increment” button is pressed, it triggers a re-render with the updated state, and the new count value is displayed.
States in React Native are essential for handling dynamic data, user input, and maintaining the state of a component throughout its lifecycle.