Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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");
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!