简体   繁体   中英

How do I prevent this infinite loop?

I need to pass foo in the arguments of useEffect so that it can use the existing array values. So I set the new values in this array but when I went to set the value, it'll call f() function again from the userEffect. How do I get out this infinit loop?

Imaginary code example goes something like this:

const [foo, setFoo] = useState<MyType>(...);

const f = () => {
    const baa = {...foo};
    for(...) {
        foo.arr[x] = y;
    }
    setFoo(foo);
}

useEffect(() => {
    f();
    g();
    // ...
}, [foo]);

JavaScript functions have access to variables in the scope above them, so you don't need to pass foo as an argument to any of these functions.

Passing foo as an agument in useEffect means that we call useEffect every time foo changes. This is what is causing your infinite loop and it doesn't seem like you want to call this every time foo changes so I would leave it out

Effect hooks run whenever their dependencies are initialised or changed. Altering a state dependency in the hook means you end up in an infinite loop.

I suspect you want some sort of computed value derived from foo . For this, there's the memo hook which will compute the new value every time its dependencies change.

const fooWithBenefits = useMemo(
  () => ({
    ...foo,
    arr: [...foo.arr.slice(0, x), y, ...foo.arr.slice(x + 1)],
  }),
  [foo]
);

You'd then use fooWithBenefits in your component instead of foo .

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