I am clear that the following is not a good practice. However, I would like to know why this snippet is not working after I click on the button if I’m using flushSync()
.
When I say that it is not working, I’m referring to the fact that the alert is showing "Hello, !" and during subsequent clicks, it shows the previous state instead of the current one.
export default function FeedbackForm() {
const [name, setName] = useState('');
function handleClick() {
flushSync(() => {
setName(prompt('What is your name?'))
})
alert(`Hello, ${name}!`);
}
return (
<button onClick={handleClick}>
Greet
</button>
);
}
2
Answers
After reading here and there, I arrived at the following conclusion:
React forces the update of the DOM using
flushSync()
, but this doesn't mean it also updates the state variable (name
) immediately because, as we know, React updates the state asynchronously.This approach would be more suitable if you want to obtain some updated information from the DOM, but you need to set a state first.
Anyways, the documentation advises against using this method unless it is absolutely necessary.
The reason why
flushSync
does not solve this problem is because it only synchronously flushes pending state updates, but it doesn’t make subsequent code synchronous. useEffect hook is called every time the name variable changes. When name is updated with the user input, the useEffect hook runs and displays the greeting message in the alert box.