skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. 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.

    import { useState, useEffect, flushSync } from 'react';
    
    export default function FeedbackForm() {
      const [name, setName] = useState('');
    
      function handleClick() {
        flushSync(() => {
          setName(prompt('What is your name?'))
        })
      }
    
      useEffect(() => {
        if (name !== '') {
          alert(`Hello, ${name}!`);
        }
      }, [name]);
    
      return (
        <button onClick={handleClick}>
          Greet
        </button>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search