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

154
Visualizações
React avoid re-calling functions after re-render

In my functional component, I have a useState variable:

const [locations, setLocations] = React.useState([]);

, I'm using useEffect to create a viewer in a div container, this viewer change locations values,

    useEffect(()=>{
        const container = document.getElementById('viewer');
        Viewer.setContainer(container);
        Viewer.onUpdate(locations => {
          setLocations(locations);
          });
        }
       })

After that I'm showing the Viewer as well as the locations values in the return of the component:

return (
 <Grid container>
  <Grid item xs={9}>
   <div id="viewer"/>
  </Grid>
  <Grid item container xs={3}>
    <Typography>
     X: {locations[0]}
     Y: {locations[1]}
     Z: {locations[2]}
    </Typography>
  </Grid>
</Grid>

);

In each change of locations values, the page is re-rendered and the also the viewer re-renders, I need a way to not re-render the viewer (the creation of the viewer is in useEffect) and just update the useState values (locations)

PS: I shrinked code to be more comprehensible

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you pass an empty array as the second parameter in useEffect the viewer will render when mounted the first time. By leaving out the dependancy array it will re-render every time. For more information on the React useEffect Hook: https://reactjs.org/docs/hooks-effect.html

useEffect(()=>{
    const container = document.getElementById('viewer');
    var child = container.lastElementChild; 
    if (child) document.getElementById('viewer').removeChild(child); 
    // deleting the viewer if it exists
    const element = document.createElement('div');
    Viewer.setContainer(element);
    Viewer.onUpdate(locations => {
      setLocations(locations);
      });
    }, [])
about 4 years ago · Juan Pablo Isaza 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