In React Native, for data that is going to change, we have to use state. You can think of it as a variable. It allows us to store data and also change it when we want.
Whenever you define a state, you need to provide an initial value for it. After that, you can use the setState function provided by React Native to change it whenever you want. Whenever setState is called and state changes, it will re-render the component in which it's being used.
To use state, you need to import useState from "react".
Syntax:
const [stateName,setStateName] = useState(<initial_value>);
Step-by-Step Implementation
Step 1: Create a React Native Project
Now, create a project with the following command.
npx create-expo-app app-name --template
Note: Replace the app-name with your app name for example : react-native-demo-app
Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app that is as clean as an empty canvas in JavaScript.
It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.
Now go into your project folder, i.e., react-native-demo
cd app-name
Project Structure:
Step 2: Run Application
Start the server by using the following command.
npx expo start
Then, the application will display a QR code.
- For the Android users,
- For the Android Emulator, press "a" as mentioned in the image below.
- For the Physical Device, download the "Expo Go" app from the Play Store. Open the app, and you will see a button labeled "Scan QR Code." Click that button and scan the QR code; it will automatically build the Android app on your device.
- For iOS users, simply scan the QR code using the Camera app.
- If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.
Step 3: Start Coding
Example 1: Open App.js file and write the below code in that file.
App.js is the main file that renders first when you run your app. We will create a state called message. We will provide an empty string as the initial value for this state. There will be one TextInput which allows user to insert any text message. We will save this text string in message state using setMessage function. And when user hit the submit button on keyboard, an alert will show with the message.
App.js:
App.js
// Import necessary components from react-native
import { StyleSheet, SafeAreaView, TextInput } from "react-native";
// Import useState hook from react
import { useState } from "react";
// Define the main App component
export default function App() {
// Declare a state variable 'message' with initial value as empty string
const [message, setMessage] = useState("");
// Render the UI
return (
// SafeAreaView ensures content is rendered within safe boundaries of a device
<SafeAreaView style={styles.container}>
{/* TextInput for user to enter a message */}
<TextInput
// Placeholder text shown when input is empty
placeholder="Enter message here"
// Value of the TextInput is bound to 'message' state
value={message}
// Update 'message' state when text changes
onChangeText={(text) => setMessage(text)}
// Apply custom styles to the TextInput
style={styles.input}
// Show alert with current message when user submits (presses enter)
onSubmitEditing={() => alert(message)}
/>
</SafeAreaView>
);
}
// Define styles for the components
const styles = StyleSheet.create({
// Style for the container view
container: {
flex: 1, // Take up the whole screen
backgroundColor: "#fff", // White background
alignItems: "center", // Center items horizontally
justifyContent: "center", // Center items vertically
},
// Style for the TextInput
input: {
fontSize: 20, // Set font size
color: "#228B22", // Set text color to forest green
fontWeight: "bold" // Make text bold
},
});
Output:
Example 2: Open App.js file and write the below code in that file.
App.js is the main file that renders first when you run your app. In this example, we will create a state called number. We will provide 0 as the initial value for this state. There will be one Button. Whenever the user presses the button, we will increment the number state by 1 using setNumber. This number will be displayed in a Text component.
Whenever the user presses the button, the state will change, and it will re-render the Text component.
App.js:
App.js
// Import necessary components and hooks from react-native and react
import { StyleSheet, SafeAreaView, Text, Button } from "react-native";
import { useState } from "react";
// Define the main App component as the default export
export default function App() {
// Declare a state variable 'number' with initial value 0 and a setter 'setNumber'
const [number, setNumber] = useState(0);
// Render the UI
return (
// SafeAreaView ensures content is rendered within safe area boundaries of a device
<SafeAreaView style={styles.container}>
{/* Display the current value of 'number' with custom styles */}
<Text style={styles.number}>{number}</Text>
{/* Button that increments 'number' by 1 when pressed */}
<Button
title="Change State"
onPress={() => {
setNumber(number + 1);
}}
/>
</SafeAreaView>
);
}
// Define styles for the components using StyleSheet
const styles = StyleSheet.create({
// Style for the container view
container: {
flex: 1, // Take up the full screen
backgroundColor: "#fff", // Set background color to white
alignItems: "center", // Center items horizontally
justifyContent: "center", // Center items vertically
},
// Style for the number text
number: {
fontSize: 20, // Set font size
color: "#228B22", // Set text color to forest green
fontWeight: "bold", // Make text bold
},
});
Output: