Search code examples
reactjsreact-hookssetstateuse-effect

How can I stop an infinite render loop if UseEffect() cannot be used in callback in React.js?


Frontend student here trying to figure out React... I just can't seem to get a hang on these hooks on React. I am trying to setState within the setArray(). This causes an infinite loop in rendering. React won't allow me to do a callback with useEffect(). I can't seem to figure out how to fix this. How can I pass my newly structured array into the state?

   const [yearsArray, setYearsArrayState] = useState([]);    

    timelineData.then((data) => {
                let yearsArrays = [];
                for (let item of data.timelineInfo) {
                    yearsArrays.push(item.year);
                }
                setArray(yearsArrays);
            });

            const setArray = (array) => {
                const passArray = new Set(array);
                const oneOfEachYear = [...passArray];
                setYearsArrayState(oneOfEachYear);
            };
        return (<div>
        {yearsArray.map((item) => (
                                <button
                                    className={style.buttonYear}
                                    onClick={() => {
                                        toggle();
                                        setClickedYear(item);
                                        console.log(clickedYear);
                                    }}  >
                        </button>
         </div>);

Solution

  • You put timelineData inside a component mount hook

    // This effect hook will be executed only once at the component mount
    useEffect(() => {
      timelineData.then((data) => {
        let newYearsArrays = [];
         for (let item of data.timelineInfo) {
           newYearsArrays.push(item.year);
         }
         setArray(newYearsArrays);
      });
    }, []);