Home > Software design >  React Native - Too Many Re-Renders
React Native - Too Many Re-Renders

Time:01-15

I am trying to create a state where it shows the visibility of some components depending on if the props are not empty. I have used an if statement as shown in the code however, it creates an error where there are too many re-renders happening. If i set a default let showComponents = false or true, everything works fine. Any idea on how to fix this issue as the visibility of the components is dependent on if the props are empty or not.

Code:

const [showcComponents, setView] = useState(false);
...
if (props.params == undefined) {
setVisibility(false);
} else {
setVisibility(true);
}

CodePudding user response:

For every update in sent to your component you are calling setVisibility(false/true). This is probably messing with the rendering method in react creating a rendering loop. You should try not to call a function outside a hook. Assuming you have a visibility variable you can try:

...
useEffect(()=>{
    if(props.params === undefined && visibility === true){
         setVisibility(false);
    }else if(props.params !== undefined && visibility === false){
         setVisibility(true);
    }
}, [props.params]
)
...

CodePudding user response:

This code will result in infinite re-render cycles. Because each time the component will render it will call setVisibility which will re-render the component

const [showcComponents, setView] = useState(false);
useEffect(()=>{
  if (props.params == undefined) {
    setVisibility(false);
  } else {
    setVisibility(true);
  }
}, [props.params])

Also you can write is shorter like this:

useEffect(()=>{
    setVisibility(props.params !== undefined);
}, [props.params])
  •  Tags:  
  • Related