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]);
CodePudding user response:
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
CodePudding user response:
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
.