avatarCkmobile

Summary

The provided web content is a tutorial on using the useState hook in a React Native application with Expo to manage and update state dynamically within functional components.

Abstract

The article on Expo React Native delves into the practical application of the useState hook, a fundamental concept in React for adding state to functional components. It begins by emphasizing the importance of states for rendering dynamic content and proceeds to demonstrate how to import and utilize the useState hook within a React Native context. The tutorial outlines a step-by-step process: importing useState from the 'react' library, initializing state variables, and creating functions to update the state. It also covers styling components, handling user interactions with buttons, and updating multiple states simultaneously. The article aims to equip developers with the knowledge to create interactive and stateful applications using React Native and Expo, providing code examples and screenshots for clarity.

Opinions

  • The author suggests that understanding React hooks is crucial for developers, recommending a course for those unfamiliar with the concept.
  • It is recommended to externalize functions for button interactions to maintain clean and readable code, especially when dealing with complex logic.
  • The article implies that the default styling of a React Native button may not be sufficient, advocating for the use of View components to apply additional styling.
  • The author expresses the ease and flexibility of using useState to manage multiple pieces of state within a single component, showcasing the simplicity of updating states with different data types.
  • The tutorial encourages following best practices by naming conventions for state variables and their corresponding setter functions.
  • It is inferred that the author values practical examples and visual aids, as the article includes multiple code snippets and screenshots to illustrate the concepts discussed.

Expo React Native — using React Hook useState()

Example of using useState Hook

Photo by Reproductive Health Supplies Coalition on Unsplash

In this article, we are going adding state so that we can output some dynamic content to the screen.

Complete React Native articles:

  1. How to build a React Native app with Expo
  2. How to Run the Expo React Native app on the emulator
  3. Expo folder and file structure
  4. Expo React Native View, Text and Style
  5. Expo React Native — using React Hook useState()
  6. How to Use TextInput Component to Change State in React Native?
  7. How to Use Expo React Native List and ScrollView
  8. How and why we use Flatlist in Expo React Native
  9. What is TouchableOpacity in Expo React Native?

We will use a react hook, so if you do not know what react hooks are at all I would suggest taking this course about react.

Basically, hook give us a way to use special functions to tap into certain features in the react library. So what we are going to do is

  1. import the useState from React
  2. Create the state and setState function
  3. Create the function to change the state

Here, we are going to be using the useState hook which means we can use states inside a functional component.

Import useState

First of all, we have to import it at the top of our project.

import React , {useState} from 'react';

Then create a state using that hook, we do this by saying Const and then in a square bracket, we have a piece of state which we are going to call “user” and then the second item is going to be a function we can use to update that state in the future, called “setUser” , that is going to be equal to the useState hook and inside the bracket we pass int the initial value of the state. We just going to pass in “Alan”

Create the state

const [user,setUser] = useState('Alan')

The user variable will be giving the value of "Alan” that is the of state we are creating.

If we want to update that value then we can use the function “setUser” to do that. What going to do is inside the Text component, we want to output some dynamic data and to do that we use curly braces and then whatever variable we want to output. The variable we want to output is “user”.

export default function App() {
const [user,setUser] = useState('Alan')
return (
<View style={styles.container}>
<Text>The username is {user}</Text>
</View>
);
}

We should see “The username is Alan” on the screen. If we want to change this in the future, we can do that using this function “setUser” . Next, we are going to create another view and this view is going to be the container for the button, just so we can style the button a little. We are gonna say style is equal to “styles.buttonstyle” Inside the view we are going to create a button. React native comes with a button component built in to the library. So go to the top and import the button component. This button component do not have an opening and a closing tag much like HTML.

What we do is to pass props to specify what text is going to be on the button itself and that prop is a title prop this will be a string. We are going to say “change user”.

export default function App() {
const [user, setUser] = useState('Alan')
return (
<View style={styles.container}>
<Text>The username is {user}</Text>
<View>
<Button title="Change user" />
</View>
</View>
);
}

The blue color button is the default style of a button. The reason we need to place this inside a View component is we can add styles to the view itself. We cannot add a style property to the button itself.

If we surround the button with a view, I can add the style property to the view and then we can style that.

<View style={styles.buttonstyle}>
<Button title="Change user" />
</View>
buttonstyle: {
marginTop: 30
},

We can give this a margin top of 30 pixels just to bring it down a little bit.

Add the change user function

we can hook up some functionality to a button is by adding an on press prop. We can directly add the function by typing

<Button title="Change user" onPress={()=>{}}/>

However, it is better to do is to externalize the function. This is because if your function has quite a bit of a logic, it is not a good practice to to do it in line because it becomes messy. We will separate the functions out unless it is just a quick one line.

const clickHandler = () => {
setUser('ckmobile')
}
<Button title="Change user" onPress={clickHandler} />

We are going to create a function “clickHandler” and inside the function, we are going to use “setUser” function. Then pass in the new value so I could change this to “ckmobile”.

We used “setUser” to update the state, we can call this function whatever we want, this is just a naming convention whatever the value we have called, then put set before it.

const [xxx, setXXX] = useState('some initial value')

We can use as much states in a component as we want. If we want to create another state we could say

const [user, setUser] = useState('Alan')
const [fruit, setFruit] = useState({name:'orange',price:5})

Then we could output the string

export default function App() {
const [user, setUser] = useState('Alan')
const [fruit, setFruit] = useState({name:'orange',price:5})
const clickHandler = () => {
setUser('ckmobile')
}
return (
<View style={styles.container}>
<Text> {user} is eating {fruit.name}, which cost $ {fruit.price} dollars</Text>
<View style={styles.buttonstyle}>
<Button title="Change user" onPress={() => { }} />
</View>
</View>
);
}

We get the fruit name by using fruit.name and fruit price by fruit.price.

We could change this if we wanted by adding in the setFruit function in the click handler.

const clickHandler = () => {
setUser('Peter')
setFruit({name:'apple',price:8})
}

Now we should see the sentence change from “Alan is eating orange, which cost $5 dollars” to “Peter is eating apple, which cost $8 dollars”.

Get free tutorials:

Follow us:

Full code:

import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [user, setUser] = useState('Alan')
const [fruit, setFruit] = useState({ name: 'orange', price: 5 })
const clickHandler = () => {
setUser('Peter')
setFruit({ name: 'apple', price: 8 })
}
return (
<View style={styles.container}>
<Text> {user} is eating {fruit.name}, which cost ${fruit.price} dollars</Text>
<View style={styles.buttonstyle}>
<Button title="Change" onPress={clickHandler} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
buttonstyle: {
marginTop: 30
},
}
});
React Hook
React
React Native
JavaScript
Mobile App Development
Recommended from ReadMedium