As mentioned in the React documentation, React takes a snapshot of the UI using its current state at the time of render. Any state change would account to a new re-render.
So an alert timed to be executed some time after and printing a state variable, prints that value of the state variable when the alert is initially scheduled to call. But when the same alert is scheduled to printing a reference variable, it prints the value of the reference variable which is present at that instantaneous time.
Here is the code :
import { useState, useRef } from 'react';
export default function Chat() {
const [text, setText] = useState('');
const dummy = useRef("");
dummy.current = text;
function handleSend() {
setTimeout(() => {
alert('Sending: ' + text);
}, 5000);
}
return (
<>
<input
value={text}
onChange={(e)=>setText(e.target.value)}
/>
<button
onClick={handleSend}>
Send
</button>
</>
);
}
In this code when the input is changed after clicking Send button, the alert shows the value of the text which was initially just before pressing Send, as evident from the fact that React takes snapshot. But when we replace text in alert by dummy.current, the alert prints the final value of the input just before the alert gets triggered. How does React schedules and substitutes value for timeout functions and how the substitution is different for state variables and reference variables?
Indra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.