'Listen for Change ONLY ONCE on a React Controlled Input

I am attempting to emit a socket event on user input but I want the event to be emitted ONLY ONCE when the value of the input changes in state and another event to be emitted ONCE when the value is cleared.

const [text, setText] = useState("");

...

useEffect(()=> {
      if (text) {
        // EMIT EVENT
        console.log("input has value emit event", text);
      } else {
        console.log("input has no value emit event");
      }
}, [text]);

...

const handleChange = e => {
    setText(e.target.value);
}

...

<Input type="text" value={text} onChange={handleChange} />

I am able to accomplish this but my code emits on every keystroke. My requirement is for both events to emit only once.

  • One when there is a value in state
  • Another when there is no value in state


Solution 1:[1]

Do the check in handleChange instead, so that you can compare the prior value to the new value.

const handleChange = e => {
    const newText = e.target.value;
    setText(newText);
    if (newText && !text) {
        console.log("input has value emit event", text);
    } else if (!newText && text) {
        console.log("input has no value emit event");
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance