React Basics Theory
What is useState ?
useState is a react hook that is used to set/create a variable inside a functional component.It basically listens to a change being done on a variable
If useState is used to set a value in functional components only then how do we manage state in class based components ?
there is a single big object to manage state in react in class based components. To set the value for a class based component we use this.setState.
Why do we need useState ? Can’t we set the values directly like angular or other frameworks ?
Since every component in react maintains a state and due to one way data binding in react, we need useState. Angular has a watch inside the framework to watch changes in a variable and make that available to different controllers, thats why it has a two way data binding and there we don’t need to explicitly maintain state.
Some important points and rules about useState ?
useState returns an array having two things: [X, setX]
Get Abhishek Gupta’s stories in your inbox
Join Medium for free to get updates from this writer.
to give a default value in useState, the syntax is:
const [name,setName] = useState("Abhishek") // here Abhishek is the default value for name. In the above example, name is a variable and setName is a function that is used to set the name variable. If we want to update the value of name, we can do it like: setName(“Abhishek2”). This will update the name from Abhishek to Abhishek2
Rules of useState:
- We should never use useState inside a loop(eg: for-loop)
- We should never use useState inside if-else(conditional statement)
const [name,setName] = useState("Abhishek")
if(tempName === 'Abhisshek'){
setName("Abhisshek"); // this is wrong
}3. It is completely fine to create n number of useState in a component.
4. useState is an asynchronous operation. Example:
const [name,setName] = useState("Abhishek")
setName("Nayan");
console.log(setName); // this might print the older value i.e. "Abhishek"
To be continued…….




