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:
Similar Reads
React vs React Native?
React and React Native, created by Facebook, are popular tools for building user-friendly apps. React is mainly used for web applications, while React Native focuses on mobile apps. They share similar concepts, but each serves a unique purpose.Table of ContentReact vs React NativeWhat is React ?What
4 min read
ReactJS State
In React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change
4 min read
Redux Store in React Native
In this article, we are going to learn about Redux Store. It is the object which holds the state of the application. The store is one of the building blocks of Redux. Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application. Â Uses of
5 min read
State Hooks in React
State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
3 min read
React Native Smart Components
In this article, we are going to learn about Smart components in React Native. The smart component is one of the categories of React Components so before diving into the smart components detail. A Component is one of the core building blocks of React and React-Native. The component is a block of cod
3 min read
Lifting State Up in ReactJS
In ReactJS, "lifting state up" is a fundamental concept that plays an important role in managing the state efficiently across different components. When building React applications, it is common for multiple components to need access to the same piece of data or state. In such cases, instead of dupl
4 min read
What is useState() in React ?
The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component. React has two types of components, one is class components which are ES6 classes that extend from React and the other
2 min read
React useState Hook
The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
5 min read
ReactJS setState()
In React, setState() is an essential method used to update the state of a component, triggering a re-render of the component and updating the UI. This method allows React to efficiently manage and render changes in the component's state.What is setState()?setState() is a method used to update the st
7 min read
What is React?
React JS is a free library for making websites look and feel cool. It's like a special helper for JavaScript. People from Facebook and other communities work together to keep it awesome and up-to-date. React is Developed by Facebook, React is a powerful JavaScript library used for building user inte
6 min read