How to setState in react-native function
Hi Guys, In this article, we are going to learn about React-native hooks example, After React 16.8 we can use hooks in our project, React hooks meanly use for state management in function. Normally in class, we use setState() to refresh data on screen but if we are using function then setState didn’t work in function, to refresh data in the function we need to use Hooks so let’s start with an example.
1. Create a new project
react-native init ReactHooksExample
2. Imports following components
import React, {useState} from 'react'; import {StyleSheet,Text,View,Button} from 'react-native';
3. Create a function instead of class
Nowadays if you create a new project react-native show function by default like below, you can delete default function and write our own class, it’s just a new way of coding nothing else. but need to use hooks in function to set data in state and reflect that change data on the screen.
export default function App(){ const [outPutText,setOutPutText] = useState('This is hooks example'); return( <View style={styles.container}> <Text style={{fontSize: 20, marginBottom:10}}>{outPutText}</Text> <Button title="Change text" onPress={()=> setOutPutText("Changed text")}/> </View> ); }
As we see in about function we use useState which is imported from React
const [outPutText,setOutPutText] = useState('This is hooks example');
in the above code, outPutText display String value from useState i.e. This is hooks example, and setOutPutText use to set the new value to State and refresh the screen with the new value.
4. Check this full code App.js
import React, {useState} from 'react'; import {StyleSheet,Text,View,Button} from 'react-native'; export default function App(){ const [outPutText,setOutPutText] = useState('This is hooks example'); return( <View style={styles.container}> <Text style={{fontSize: 20, marginBottom:10}}>{outPutText}</Text> <Button title="Change text" onPress={()=> setOutPutText("Changed text")}/> </View> ); } const styles= StyleSheet.create({ container:{ flex:1, backgroundColor:'#FFFFFF', alignItems:'center', justifyContent:'center' } })
As we see in the above source code, I added anonymous arrow function on Button onPress and setOutPutText new Text this update state value and automatically refresh the screen as you see below
5. Output:
Thank you 🙂