Home > front end >  React too many rending with useState
React too many rending with useState

Time:10-14

My Code :

import Item from './Item_att.js';
import axios from 'axios';

const Attraction_list = () => {
...
const [maindata, setMainData] = useState([]); //setData
const [postsPerPage] = useState(6);
...

let attList = async (areaCode, cityCode) => { //approach openAPI
    const url = `...`;
    try {
        const {data: res} = await axios.get(url)
        const list = res.response.body.items.item;

        console.log("rendering!")
        setMainData(list);
    } catch (err) {
        console.log(err);
    }
}

...

attList(1, 1).then(data => {console.log("then");}) //make maindata
const currentPosts = (tmp) => {    //slice data
    return tmp.slice(indexOfFirst, indexOfLast);
}

...

return (
    <div>
        ...
        <Item rlist={currentPosts(maindata)} moveTo={moveTo} area={area} city={"강남"}></Item>
    </div>
);
};

export default Attraction_list;

Function attList bring data from openAPI. Function currentPosts is executed when component Item rendering, it return sliced list.

I think they executed only one time,

Result : Too many rerendering on this program. Function attList and function currentPost executed to many. I don't know Why.

Why rerendering so much?

CodePudding user response:

You should call the function attList inside a useEffect hook, else it will be called on each rerender of the component.

React.useEffect(()=>{

    attList(1, 1)

},[])

CodePudding user response:

When you call

setMainData(list);

inside your attList function, react will rerender your component as there is a state change. This will then run your attList function again which is what is causing the loop.

To prevent this behaviour you can use the useEffect react hook to call the attList function once on the first render and only on the first render.

https://reactjs.org/docs/hooks-effect.html

CodePudding user response:

You have made an infinity loop because the attList will execute setMainData which will then rerender the component again and therefor execute the attList again.

This is why you should use the useEffect hook, to make sure that the attList is only executed when you wan't it to. If you do as shown above, then it will only happen when the component is mounted.

  • Related