Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
React use effect causing infinite loop

Am new to react and am creating a custom select component where its supposed to set an array selected state and also trigger an onchange event and pass it to the parent with the selected items and also get initial value as prop and set some data.

let firstTime = true;
const CustomSelect = (props)=>{
    
    const [selected, setSelected] = useState([]);

     const onSelectedHandler = (event)=>{
         
        // remove if already included in the selected items remove 
        //otherwise add

         setSelected((prev)=>{
            if (selected.includes(value)) {
                values =  prevState.filter(item => item !== event.target.value);
             }else {
                values =  [...prevState, event.target.value];
             }
            return values;
         })

         // tried calling props.onSelection(selected) but its not latest value
     }

   //watch when the value of selected is updated and pass onchange to parent 
   //with the newest value
   useEffect(()=>{
     if(!firstTime && props.onSelection){
          props.onSelection(selected);
      }
    firstTime = false;
   },[selected])
     
   
   return (<select onChange={onSelectedHandler}>
              <option value="1"></option>
            </select>);

 };

Am using it on a parent like

 const ParentComponent = ()=>{

   const onSelectionHandler = (val)=>{
      //do stuff with the value passed
    }

   return (
    
     <CustomSelect initialValue={[1,2]} onSelection={onSelectionHandler} />

  );

  }

 export default ParentComponent

The above works well but now the issue comes in when i want to set the initialValue passed from the parent onto the customSelect by updating the selected state. I have added the followin on the CustomSelect, but it causes an infinite loop

const {initialValue} = props
useEffect(()=>{
  //check if the value of initialValue is an array 
  //and other checks
   setSelected(initialValue) 
 
 },[initialValue]);

I understand that i could have passed the initialValue in the useState but i would like to do a couple of checks before setting the selected state. How can i resolve this, am still new to react.

almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In your //do stuff with the value passed you are most likely update the states of your component parent component and it causes to rerender parent component. When passing the prop initialValue={[1,2]} creates a new instance of [1,2] array on each render and causes the infinite render on useEffect. In order to solve this, you can move the initialValue prop to somewhere else as const value like this:

const INITIAL_VALUE_PROP = [1,2];
const ParentComponent = ()=>{

   const onSelectionHandler = (val)=>{
      //do stuff with the value passed
    }

   return (

     <CustomSelect initialValue={INITIAL_VALUE_PROP} onSelection={onSelectionHandler} 
     />

  );

}

export default ParentComponent
almost 4 years ago · Santiago Trujillo Relatório

0

Okay, so the reason this is happening is that you're passing the initialValue prop as an array, and since this is a reference value in JavaScript, it means that each time it's passed(updated), it's passed with a different reference value/address, and so the effect will continue to re-run infinitely. One way to solve this is to use React.useMemo, documentation here to store/preserve the reference value of the array passed, not to cause unnecessary side effects running.

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda