Why is an infinite loop created when I pass a function expression into the useEffect dependency array? The function expression does not alter the component state, it only references it.
// component has one prop called => sections
const markup = (count) => {
const stringCountCorrection = count + 1;
return (
// Some markup that references the sections prop
);
};
// Creates infinite loop
useEffect(() => {
if (sections.length) {
const sectionsWithMarkup = sections.map((section, index)=> markup(index));
setSectionBlocks(blocks => [...blocks, ...sectionsWithMarkup]);
} else {
setSectionBlocks(blocks => []);
}
}, [sections, markup]);
If markup altered state I could understand why it would create an infinite loop but it does not it simply references the sections prop.
So I'm not looking for a code related answer to this question. If possible I'm looking for a detailed explanation as to why this happens.
I'm more interested in the why then just simply finding the answer or correct way to solve the problem.
Why does passing a function in the useEffect dependency array that is declared outside of useEffect cause a re-render when both state and props aren't changed in said function?
useEffect
? – Headdressmarkup
to be a dependency in this case? You know it is going to change reference on every render. So, if you need to depend on it, don't useuseEffect
. If you don't need to depend on it, don't include it. Putting in auseCallback
in this case is equivellent to not including it in the dependency list. Even if you have something in theuseCallback
dependency list, just move that to theuseEffect
dependencies. IMO, there is no reason to include it in the dependency list and there is no reason to useuseCallback
. – Depreciation