Home > Net >  React How to prevent useEffect execution when input is blank?
React How to prevent useEffect execution when input is blank?

Time:01-18

I am using useEffect for username field to check if the typed username by user already exists in the database

const[username,setUsername]=useState('');


useEffect(()={
 // Logic here to fetch and check if typed username already exists
},[username]);

I want to execute this useEffect only when username is non-blank. It renders this useeffect on initial page render, which I do not want to happen.

useRef is preventing only on initial render, but every time this username field is blank from non-blank, this should not execute.

Any help on this, please?

CodePudding user response:

Just add an if condition

useEffect(()={
   if(usename){
     // Logic here to  
   }
},[username]);

CodePudding user response:

This should work:

const[username,setUsername]=useState('');


useEffect(()={
 // Logic here to fetch and check if typed username already exists
},[username]);

const changeHandler = (event) => {
    const username = event.target.value;
    if(username === '') return;
    setUsername(username);
}


<input onChange={()=>changeHandler(event)}/>

  • Related