Is it possible to update one state in React and in the same render, can we use the updated value to update another state?
import "./styles.css";
import {useState} from 'react';
export default function App() {
const [num, setNum] = useState(0)
const [txt, setTxt] = useState(0)
handleClick= () =>{
setNum(num+1)
setTxt(num+1)
}
return (
<div className="App">
<input type="submit" value="button" onClick={handleClick} />
<h1>{num}</h1>
<h1>{txt}</h1>
</div>
);
}
In the above example, both num and txt are initially set to 0. Clicking the button for the first time would increase both num and txt to 1 and it would update both to 2 when clicked again and so on.
Is there way to get the num updated to 1 as soon as setNum(num+1)
is called, so that it can update it from 0 to 1 and so while calling setTxt(num+1)
, it can update it directly to 2?