I recently learnt that React renders a snapshot of the UI before the set function is called to change the state and re-rendering is perform. The entire JSX works with the previous state. For example:
import { useState } from 'react';
export default function FeedbackForm() {
const [name, setName] = useState('');
function handleClick() {
setName(prompt('What is your name?'));
alert(`Hello, ${name}!`);
}
return (
<button onClick={handleClick}>
Greet
</button>
);
}
After giving a name in the prompt box, the alert still says : Hello, !
. It is because the alert takes name from the first rendering which is null.
According to the above description this code:
import { useState } from 'react';
export default function Form() {
const [to, setTo] = useState('Alice');
const [message, setMessage] = useState('Hello');
function handleSubmit(e) {
e.preventDefault();
alert(`You said ${message} to ${to}`);
}
return (
<form onSubmit={handleSubmit}>
<label>
To:{' '}
<select
value={to}
onChange={e => setTo(e.target.value)}>
<option value="Alice">Alice</option>
<option value="Bob">Bob</option>
</select>
</label>
<textarea
placeholder="Message"
value={message}
onChange={e => setMessage(e.target.value)}
/>
<button type="submit">Send</button>
</form>
);
}
So as onchange event fires, the state of both the variable to and message changes, and when the form is submitted, the alert should show : You said Hello to Alice
rather it shows alert which includes new to
and new message
.
Where I am getting wrong?