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

153
Views
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 answers
Answer question

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 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!