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

135
Visualizações
How do I update state but not trigger the infinite useEffect loop?

I'm trying to update state in a higher-order component from a child. My solution is to set state to true after setting tags. useEffect runs when state is true, firstly updating state in the parent component and then updating state to false, which halts its invocation. My aforementioned solution is the only way I've managed to prevent useEffect's infinite loop.

  const Student = ({ 
  appendTags,
  student: {
    id: studentId,
    firstName,
    lastName,
    pic,
    email,
    company,
    skill, 
    grades,
    tags: studentTags
  }}) => {
  const fullName = `${firstName} ${lastName}`;
  const [tag, setTag] = useState('');
  const [tags, setTags] = useState([]);
  const [stateUpdated, setStateUpdated] = useState(false);
  const [displayGrades, setDisplayGrades] = useState(false);
  
  const onTagsSubmit = e => {
    if (tag.length) {
      e.preventDefault();
      
      setTags(prevState => [...prevState, tag]);
      setStateUpdated(true);
      setTag('');
    }
  }
  useEffect(() => {
    if (stateUpdated) {
      appendTags(studentId, tags);
      setStateUpdated(false);
    };
  }, [stateUpdated, setStateUpdated, tags, appendTags, studentId]);
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Looks like this is what we have, if you remove stateUpdated.

I presume than on appendTags() call the parent component changes its state and gets re-rendered. After that the appendTags function is recreated. The child component Student is recreated, too. Student's useEffect sees that one of the dependencies, appendTags, has changed, so it has to be re-executed. It calls the appendTags() and we have a loop.

To fix it, you need to wrap appendTags into useCallback hook inside the parent component:

const appendTags = useCallback((id, tags) => {
  // update local state
}, []);
// ...
return <Student appendTags={appendTags} /* (...) */ />
about 4 years ago · Santiago Gelvez 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