Complete explanation of useState in React
According to the latest react documentation hooks are a new addition to react version 16.8. Hooks generally help us to use the state and other features of React without writing class-based components in React. The useState hook in react is used for managing the state of a functional component in react. The most important benefit of using useState is that the state will be updated as soon as react will re-render the component on its own without reloading the page.
If you want to use useState in your component then you need to import it from react first and there is a specific format for using useState in react which is discussed below:
Let us now create a component and apply useState to it so that we can know more about how it works.
In the above component, we have created a inputValue useState and by default we are passing Ajay to it. We have taken an input field that will take text input from the user. In the above example we have taken newChangeValue which we will set when the user enters some value into the input element. Here we are generally using the onchange attribute to listen to an input change.
The above code generally displays an input field that when typed passes its current value to the onChange function. Now we will create an onChange function in which we will pass the event as a parameter. The purpose of taking an event as a parameter is we can get the current input value and when the user changes the value we can easily change it accordingly. For this we have taken const newVal=e.target.value. And now we are just setting the newChangeValue with newVal.
Equivalent Class Example
If you want to do the same thing using a class-based component in React then you can do it as mentioned below: