I know how to use prevState in new State, I want to know how does it actually works ?? How does this functionality works ?? why on putting in ‘prevValue’ in ‘setFullName’ function changes its value ?
import React, { useState } from "react";
function App() {
const [fullName, setFullName] = useState({
firstName: "",
lastName: ""
});
function handleChange(event) {
let value = event.target.value;
let name = event.target.name;
setFullName((prevValue) => {
if (name === "fName") {
return {
firstName: value,
lastName: prevValue.lastName
};
} else if (name === "lName") {
return {
firstName: prevValue.firstName,
lastName: value
};
}
});
}
return (
<div className="container">
<h1>
{fullName.firstName} {fullName.lastName}
</h1>
<form>
<input onChange={handleChange} name="fName" placeholder="First Name" />
<input onChange={handleChange} name="lName" placeholder="Last Name" />
<button>Submit</button>
</form>
</div>
);
}
export default App;