Trying to understand the state update -UseState React hook. setting the message inside onchange event of text area re-renders immediately and able to see the updated message state (handleChangeMessage).
But while updating the state inside the on-Keypress event doesn't display the updated message text immediately (handleKeyPressMessage).
Why the handleKeyPressMessage- doesn't render the latest value but handleChangeMessage does? The Irony here is the log statement inside handleKeyPress executes first before the onchange event.
code-sandbox link: https://codesandbox.io/s/usestate-01-forked-lvyio?file=/src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Message = () => {
const [handleChangeMessage, setHandleChangeMessage] = useState("");
const [sendButtonClass, setSendButtonClass] = useState("send-disabled");
const [handleKeyPressMessage, setHandleKeyPressMessage] = useState("");
const handlechange = (e) => {
console.log("change");
setHandleChangeMessage(e.target.value);
};
const handleKeyPress = (e) => {
console.log("key");
setHandleKeyPressMessage(e.target.value);
if (handleChangeMessage == "") {
setSendButtonClass("send-disabled");
} else {
setSendButtonClass("send");
}
};
return (
<div>
<input
type="text"
value={handleChangeMessage}
placeholder="Enter a message"
onChange={handlechange}
onKeyPress={handleKeyPress}
/>
<button className={sendButtonClass}>Send</button>
<p>
"message updated via onChange event ======> : "
<strong>{handleChangeMessage}</strong>
<br />
"message updated via onKeyPress event =====> : "
<strong>{handleKeyPressMessage}</strong>
</p>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);
UPDATE
The issue here is keypress event is triggered first before onchange event(updates handleChangemessage). So the input element has the outdated value in HandleKeyPress event(e.target.value i.e handleChangemessage) Changing the keypress event to keyup will resolve the issue as Abhishek suggested