'useState and if statement causing Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

What I'm attempting to create is a React component which conditionally renders when the value of the prop boxToggle is true, and also returns null when the user clicks the exit button. What I done to implement this, was to create a local useState called displayUI and assigned the displayUI to true or false using a if statement (this may be the problem, but I cant pinpoint why) depending on the boxToggle prop and inside the onClick of the exit button.

But I receive this error inside the component:

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Here is the parent component (im using react-three-fiber)

import React, { useRef, useState } from 'react';
import './App.css';

//Packages
import * as THREE from 'three';
import { Canvas, useFrame } from 'react-three-fiber'



import {Box, OrbitControls} from 'drei';


//Components
import Header from './components/Header';
import Homepage from './components/Homepage';
import { Light } from 'three';

//Functions

  //Main App Function
function App() {
  

  const [boxToggle, setboxToggle] = useState(false);  

  return (
    <div className="App">
      <Header/>
      <Homepage boxToggle={boxToggle}/>
      <Canvas
        colorManagement 
        camera={{position: [0, 5, 10], fov: 60}}
        shadowMap
      >
        <Lights/>
        <RotatingBox
          onClick={()=> setboxToggle(true)}
        />
        <Floor/>
        {/* <OrbitControls/> OrbitControls causes problems with the Raycasting (onClick)*/}
      </Canvas>
    </div>
  );
}

  //Scene Lights
const Lights = () => {

  return (
    <>
      <directionalLight
        intensity={1.5}
        position={[0, 10, 5]}
        castShadow
        shadow-mapSize-width={1024}
        shadow-mapSize-height={1024}
        shadow-camera-far={50}
        shadow-camera-left={-10}
        shadow-camera-right={10}
        shadow-camera-top={10}
        shadow-camera-bottom={-10}
      />
      <ambientLight
        intensity={0.3}
      />
    </>
  )
}

  //Meshes
const RotatingBox = ({onClick})=> {

  const box = useRef();

  const [boxSize, setBoxSize] = useState(false);  

  useFrame(()=>(
    box.current.rotation.y = box.current.rotation.x += 0.01,
    console.log(boxSize)
    )
  )

  return (
      <>
        <Box
          args={ boxSize ? [1, 1, 1]: [2, 2, 2]}
          ref={box}
          castShadow
          onClick={onClick}//cant get onClick Working at all, drei or R3F
          onPointerOver={onClick= ()=> setBoxSize(true)}
        >
          <meshStandardMaterial 
            
            cast
            attach="material" 
            color='yellow'
          />
        </Box>
      </>
  )
}

const Floor = () => {
  return (
    <>
      <mesh
        onClick={()=> console.log("click")} 
        receiveShadow 
        rotation={[-Math.PI / 2, 0, 0]} 
        position={[0, -3, 0]}
      >
        <planeBufferGeometry attach='geometry' args={[100, 100]}/>
        <meshStandardMaterial opacity={1} attach='material'/>
      </mesh>
    </>
  )
}

export default App;

and the child Homepage component

import React, { useState } from 'react';
import styles from './Homepage.module.css'

const Homepage = ({boxToggle}) => {

    const [displayUI, setDisplayUI] = useState(false);

    if (boxToggle) { 
        setDisplayUI(true);
    }


    if (displayUI === true) {
        return (
            <div className={styles.container}>
                <button onClick={() => setDisplayUI(false)} className="exit">X</button>
                <div className={styles.title}>
                    <h1>Homepage</h1>
                </div>
                <div className={styles.menu}>
                    <h3>Option 1</h3>
                    <h3>Option 2</h3>
                    <h3>Option 3</h3>
                </div>
            </div>
        )
    } else return null
}

export default Homepage

Ive tried other stackoverflow answers, but i cant apply them to mine. Most of them are to do with useEffect, or theyre missing a arrow function. This ones got me puzzled i dont even know where to start because im not familiar with Hooks. Thanks



Solution 1:[1]

I believe the issue is cause by your Homepage component.

const Homepage = ({boxToggle}) => {

    const [displayUI, setDisplayUI] = useState(false);

    //this generate error because it update the state directly when render
    /*if (boxToggle) {   
        setDisplayUI(true);
    }*/

    //we can fix it by wrap it with a useEffect hook so this effect only trigger when the boxToggle value change
    
    React.useEffect(()=>{
       if (boxToggle) {  
        setDisplayUI(true);
       }
   
    }, [boxToggle])  // <--- dependency that trigger the function call


    if (displayUI === true) {
        return (
            <div className={styles.container}>
                <button onClick={() => setDisplayUI(false)} className="exit">X</button>
                <div className={styles.title}>
                    <h1>Homepage</h1>
                </div>
                <div className={styles.menu}>
                    <h3>Option 1</h3>
                    <h3>Option 2</h3>
                    <h3>Option 3</h3>
                </div>
            </div>
        )
    } else return null
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wei J. Zheng