Using React Hook useState in ReactNative
Hooks are introduced in React 16.8. Hooks are used in functional Components.
We will be learning to write code using React Hook useState. But, before let me show you an example how we used to update our state without using useState or with class component.
import React from 'react'
import { View, Text, TextInput, StyleSheet } from 'react-native'
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
marginHorizontal: 20,
},
textinputContainer: {
backgroundColor: 'lightgrey',
height: 50,
borderRadius: 10,
borderBottomWidth: 1,
paddingHorizontal: 10,
marginVertical: 20,
},
textContainer: {
flexDirection: 'row',
},
})
class App extends React.Component {
state = {
value: '',
}
render() {
return (
<View style={styles.container}>
<View style={styles.textContainer}>
<Text>Value:</Text>
<Text>{this.state.value}</Text>
</View>
<TextInput style={styles.textinputContainer} onChangeText={(text) => this.setState({ value: text })} />
</View>
)
}
}
export default App
Here, above we are updating our state with this.setState({}).
Now, lets dive into our useState react hook.
import React, { useState } from 'react'
import { Text, View, StyleSheet, TextInput } from 'react-native'
const styles = StyleSheet.create({
wrapper: { flex: 1, justifyContent: 'center', marginHorizontal: 20 },
textInputWrapper: {
backgroundColor: 'lightgrey',
height: 50,
borderRadius: 10,
borderBottomColor: 'grey',
borderBottomWidth: 1,
marginTop: 30,
paddingHorizontal: 10,
},
inboxwrapper: {
flexDirection: 'row',
},
})
const App = () => {
const [inputValue, setinputValue] = useState('')
return (
<View style={styles.wrapper}>
<View style={styles.inboxwrapper}>
<Text>Value:</Text>
<Text>{inputValue}</Text>
</View>
<TextInput onChangeText={(text) => setinputValue(text)} style={styles.textInputWrapper} />
</View>
)
}
export default App
Conclusion:
// without React hooks
onChangeText={text => this.setState({value: text})}
// with React hooks
onChangeText={text => setinputValue(text)}
If you have any confusion, regarding the react hooks. Please feel free to comment, and I will try to answer it.
2 Replies to “Using React Hook useState in ReactNative”