How can I make useEffect
have control over the component update?
I have this:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/api/data")
.then((res) => res.json())
.then((res) => {
setData(res.data);
})
.catch((err) => console.error(err));
}, []);
This brings me the information once but if I do something with an item within data
the change is not shown in the component that shows that data
.
If I use this:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/api/data")
.then((res) => res.json())
.then((res) => {
setData(res.data);
})
.catch((err) => console.error(err));
}, [data]);
It stays in an infinite update loop.
I only want it to change if any data
change occurs, so that it doesn’t remain in an infinite loop, how could I achieve this?
Exhibit:
In some useEffect
s that I have used it asks me for dependencies but this particular one does not do so.
2
Answers
Try using setData instead of setStrores in the code
In the first case, you will get the
res.data
once sinceuseEffect
without dependency trigger once when component rendered.In the second case,
setData
is called insideuseEffect
which mean the effect will run infinite time sincedata
being set every render