简体   繁体   中英

setState with function creates infinite loop

I need to create some data and set it as an initial state.

const initialState = [
{
    name: "Joe",
    email: "joe@lorem.com",
    username: "FOOOO",
    website: "www.foosite.com",
    address: {
        city: "New York",
        street: "Times Square",
        suite: "244/78",
        zipcode: "00000",
    },
},
];

Here I just recreate that data multiple times, as I need more of them.

const createSkeletons = useCallback(() => {
    const arr = [];
    let i;
    for (i = 0; i < 20; i++) {
        initialState.forEach((item) => arr.push(item));
    }
    console.log(arr);
    return arr;
}, []);

And here set them as a state while genuine data are fetching. The created data will be rendered meanwhile.

useEffect(() => {
    setIsFetching(true);
    const initial = createSkeletons();
    setDesigners(initial);
    axios.get(`site.com`).then((res) => {
        setIsFetching(false);
        //setDesigners(res.data);
    });
}, [isFetching, createSkeletons]);

However, this creates an infinite loop. What am I doing wrong?

You don't need to use useEffect to set the initial state, you can do that directly in the useState :

const [designers, setDesigners] = useState(createSkeletons());

useEffect(() => {
    setIsFetching(true);
    axios.get(`site.com`).then((res) => {
        setIsFetching(false);
        setDesigners(res.data);
    });
}, []);

useEffect with [isFetching, createSkeletons] is executed each time isFetching changes, the problem is that you modify isFetching in the useEffect, so it will create a loop. just removes isFetching from the parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM