0

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

1 Answer 1

2

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);
      });
    }, [])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.