Hello world,
we will discuss on how to use the useState hook in Reactjs with examples.
so let's start with an example where we are going to use old style react state management.
import React from 'react';
import { Text, View, TextInput } from 'react-native';
export default class App extends React.Component {
state = {
name: '',
}
render() {
return (
<View>
<TextInput
onChangeText={text => this.setState({name: text})}
value={this.state.name}
placeholder="enter here"
/>
</View>
);
}
}
so here we are using state with
this.state.name
and updating it with
this.setState({name: text})
let me explain how useState works here before going further. React 's useState gives us two objects.
const [state, action] = useState("")
first is the actual state and the second is the action to update the current state and when we initialize it we provide the initial state in it, for example, here we are giving a blank string state.
useState('');
now let's do the same example with React hooks
import React, { useState } from 'react';
import { Text, View, TextInput } from 'react-native';
const App = (props) => {
const [name, setName] = useState("")
return (
<View style={styles.container}>
<TextInput
onChangeText={text => setName(text)}
value={name}
placeholder="enter here"
/>
</View>
);
}
export default App;
we can access the state without this
keyword because in the last example we are using a functional component so the variables are accessible within the function without this
keyword.
// without React hooks
value={this.state.name}
// with React hooks
value={name}
and to update the state we can just call the second argument by passing the new state.
// without React hooks
onChangeText={text => this.setState({name: text})}
// with React hooks
onChangeText={text => setName(text)}
this is how we can use useState in Reactjs and React Native. I hope you liked it. if something I missed or you have questions related to it you can ask in comments.
Top comments (3)
What's the difference of value and onChangetext here?
value is the current state of the text input and onChangeText is a function that gives the updated value/text on every change.
Thank you for clarifying that for me!