useState() Hook - in React js
useState() Hook
What is State?
The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component
What does calling useState
do?
It declares a “state variable”. Our variable is called count
but we could call it anything else, like state
.
What do we pass to useState
as an argument?
The only argument to the useState()
Hook is the initial state. In Classes the state should be Object, but in Hooks it does not need to be Object. We can keep a number or a string if that’s all we need. In our example,0
is the initial state.
What Do Square Brackets Mean?
You might have noticed the square brackets when we declare a state variable:
This JavaScript syntax is called “array destructuring”. It means that we’re making two new variables count
and setCount
, where count
is set to the first value returned by useState
, and setCount
is the second.
What does useState() give us?
useState
gives us two variables and we can name our two variables whatever we want. Just know that:
- The first variable is the value. Similar to
this.state
- The second variable is a function to update that value. Similar to
this.setState
The final part to useState is the argument that we pass to it. The useState argument is the initial state value. In the case of our counter, we started at 0.
Here in this example you will see , how to use useState(0) , number values
Here in this example you will see , how to use useState("string") , string values
and with ternary operator ::
useState with Object..using onChange() Event
onChange() Event with Radio Button
Show & Hide , Events in Functional Component