I was changing a state between renders and logging that value on every time the state changes via useEffect. I noticed my console is showing this error bellow:
image of console showing the error.
I’m not understanding why is it that I’m getting this error. It would be very helpful if someone could explain why is my console showing this error.
Here’s the code if it helps:
import React, { useEffect, useState } from "react";
import Item from "./Item";
import { Item as ItemType } from "../types";
const Content: React.FC = () => {
const [items, setItems] = useState<Array<ItemType>>([
{ id: 1, checked: false, item: "Banana" },
{ id: 2, checked: false, item: "Potato" },
{ id: 3, checked: false, item: "Charger" },
]);
const onItemChecked = (id: number) => {
const _items = items.map((item) =>
item.id === id ? { ...item, checked: !item.checked } : item
);
setItems(_items);
};
const onItemDeleted = (id: number) => {
const _items = items.filter((item) => item.id !== id);
setItems(_items);
};
useEffect(() => {
console.log(items);
}, items);
return (
<main>
<ul>
{items.map((item) => (
<Item
item={item}
key={item.id}
onItemChecked={onItemChecked}
onItemDeleted={onItemDeleted}
/>
))}
</ul>
</main>
);
};
export default Content;
3
Answers
The
useEffect
dependency array requires stable values between renders. Changing the array’s reference triggers the effect. To logitems
when it changes, use an empty dependency array[]
or compare the array contents using methods likeJSON.stringify
.if you want to include the items array in the dependency array and want the effect to run whenever the items array changes,
Should be
Could you update your code like below?
Your way to use
useState
is not correct.