I have a question regarding hooks and set State. Let's take very basic example. Suppose I have one input box and button, which is a very common use case. Whenever i type in input box, and click on button, button click handler should reflect the latest state. On stackoverflow, I saw below code to do the activity:
const input = props => {
const [textInput, setTextInput] = React.useState('');
const handleClick = () => {
console.log(textInput);
props.send(textInput);
}
const handleChange = (event) => {
setTextInput(event.target.value);
}
return (
<div>
<input onChange={handleChange} placeholder="Type a message..." />
<div onClick={handleClick} className="icon">
<i className="fa fa-play" />
</div>
</div>
)
}
Isnt above setTextInput(event.target.value); input async as react does batching? So when user clicks on submit, how do i know that state is actually updated? . This is a very basic use case and i don't want to use useRef as this must be a common problem or am i missing something?
Note: In above solution, we want to read the state only after both the conditions are satisfied:
In my limited knowledge, setState is in fact asynchronous. It does not interrupt other processes to carry out setting the state. It is queued to be executed on the next batch.
The situation you are talking about here will never have the async nature of setState cause problems. The action of the user clicking will always happen after the newState is set.