Search code examples
reactjsreact-hooksuse-effect

react hook useEffect infinite loop


Below is my code snipet. When i receieve my prop and try to useSate, i recieve this infine loop even after following number of solutions.

const App = ({ center }) => {
  const position = [-1.29008, 36.81987];

  const [mapCenter, setMapCenter] = useState();

  useEffect(() => {
    if (center && center.length > 0) setMapCenter(center);
    else setMapCenter(position);
  }, [center, position]);


return (<div> </div>)

}

export default App;

Solution

  • The issue is that you are defining position array in functional component and its reference gets changed on each re-render and hence the useEffect executed again.

    You can move declaration of position out of component since its a constant like

    const position = [-1.29008, 36.81987];
    const App = ({ center }) => {
    
    
      const [mapCenter, setMapCenter] = useState();
    
      useEffect(() => {
        if (center && center.length > 0) setMapCenter(center);
        else setMapCenter(position);
      }, [center, position]);
    
    
    return (<div> </div>)
    
    }
    
    export default App;
    

    or remove the dependency of position from useEffect

    const App = ({ center }) => {
      const position = [-1.29008, 36.81987];
    
      const [mapCenter, setMapCenter] = useState();
    
      useEffect(() => {
        if (center && center.length > 0) setMapCenter(center);
        else setMapCenter(position);
      }, [center]);
    
    
    return (<div> </div>)
    
    }
    
    export default App;