MERN stack:How to use UseState in the functional components and how to use the previous state object in the state method
Hey I am deep shah.I am MERN stack Enthusiast. So let's talk about useState Hook
What are hooks? => With the help of hooks code can seem more declarative and also no branches ..so it's easier to follow.
Hooks let you always use functions instead of having to constantly switch between functions, classes, higher-order components
useState: =>It allows you to have state variables in functional components.
How to get started with it =>here we go
import React,{useState} from 'react'
let's take simple example=> here
const [word,setWord]=useState("");
so this is similar to this.state.word and this.setState in class(Js) and also here the names can be anything ..according to the developer's choice. this syntax returns values in pair(Called as array destructuring) here the word is initiated with empty string.. if you want to update the value then you have to use the method setWord
setWord("MERN stack");
so that's how we can make the use of useState Hook
suppose we have an object like=>
{
name:"deepshah1309",
Interest:"MERN",
Course:"CSE"
}
Code:here I have showed the way to use objects in useState
import React,{useState} from 'react';
function Person()=>{
const [state,setState]=useState({name:"deepshah1309",Interest:"MERN",Course:"CSE"});
return(
//display the state object content
<div>
{state.name}
{state.Interest}
{state.Course}
</div>
)
}
}
export default Person;
Suppose I want to update name property of the object then => setState({...state,name:"deepshah"); ...state maintains previous object and other field name here changes my previous name with "deepshah"
Thanks for Reading