About Lesson
In this React Native lesson we are going to learn about React Native useState Hooks, so as i have already said that you can use stats inside a functional component using React Hooks, a Hook is a kind of function that lets you “hook into” React features. For example, useState is a Hook that lets you add state to function components.
So this is my component for creating react native useState hooks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import React, {useState} from 'react'; import {Text, View, Button} from 'react-native'; const StateHooks = () => { const [name, setName] = useState("GeeksCoders") return( <View> <Text style = {{fontSize:20, padding:20}}>{name}</Text> <Button title = "Click" onPress = {() => setName("Parwiz Forogh")} /> </View> ) } export default StateHooks; |
first of all you need to import useState hook form React.
1 |
import React, {useState} from 'react'; |
And after that we are going to call useState, calling useState does two things:
- it creates a “state variable” with an initial value—in this case the state variable is Name and its initial value is a simple string.
- it creates a function to set that state variable’s value and that is setName
1 |
const [name, setName] = useState("GeeksCoders") |
Now we can add our newly created component in the App.js.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import StateHooks from './components/StateHooks'; export default function App() { return ( <View> <StateHooks/> </View> ); } |
First run this command.
1 |
npm start |
And after that run your application, click on the button you will see that the text is changed.