React state updates are asynchronous, so you shouldn't do things like this:
const _handleChange = (event) => {
setEmail(event.target.value);
_updateEmailPermissions(email);
};
Because the setter might not actually finish before the update function is called.
But what if we have something like this?
const handleSubmit = (event) => {
event.preventDefault();
_updateEmailPermissions(email);
// ...
}
return (
<form onSubmit={handleSubmit}>
<SomeComponent onChange={(event) => setEmail(event.target.value)} />
<button>Submit</button>
</form>
)
Is this considered safe? I haven't managed to break it no matter how fast I try to jump from changing SomeComponent to submitting the form, but I wonder if there's any case in which the handleSubmit function will work with an outdated email.
If it's not safe, what's a better way of doing this considering I need email to be usable in the form submit event?
Background
My particular use case is a bit more complex, but I think it reduces to the above example: I actually have a table (AG Grid) in a child component that calls a setRows React state setter passed as a prop to it whenever a row changes. This is fine for me because I will only ever have a few rows. The parent component then uses rows in a form submit event like above. I need to know if the rows it uses are always the ones actually displayed by the table or if the asynchronous nature of state setters might ever let things get out of sync between row change and form submission.