I have trouble with updating data of a parent component inside of a child component. I'm using React 18.2.0 with functional components.
To provide a basic code example for my problem:
Parent.js
export default function Parent() {
const [counter, setCounter] = useState(0);
const [stuff, setStuff] = useState([]);
const [items, setItems] = useState("");
const [size, setSize] = useState(2);
useEffect(() => {
refresh();
}, [size]);
function refresh() {
let newStuff = Array(size).fill().map((_, index) => {
return <Child key={index} counter={counter} items={items} setItems={setItems}/>;
});
setStuff(newStuff);
}
}
...
Child.js
export default function Child({counter, items, setItems}) {
useEffect(() => {
refresh();
}, [counter]);
function refresh() {
setItems(items + "test");
}
}
So to explain it in a basic way: I have parent who has a counter, a string and an array as useState. The array "stuff" has many child components in one layer, the string "items" is here to be edited from the different child components.
The plan is to manually (e.g. through a button click) increment "counter", so that the useEffect in all child components fires and thus items should be edited.
But the problem is that the useEffect in the child component does not register that "counter" is incremented even though it is a useState variable.
So how can I go about this? I have one parent component which has a dataset which is modified by many child components in which lie in the parent component.
What am I missing? Do I have to use some other react functionalities (e.g. useRef, useContext or something)?