I have this code :
function Parent(props) {
const [items, setItems] = useState([]);
const [itemArr, setItemArr] = useState([]);
const [reRender, setReRender] = useState(false);
useEffect(() => {
let _items = items.slice(0).reverse().map((item, idx) => {
return {
type: {
subject: item.type,
type: "text"
},
child: {
subject: <Child
data = {item}
></Child>,
type: "inline"
},
}
});
setItemArr(_items);
}, [reRender])
function newItem(info) {
let [date, time] = getDate();
let tmp = items;
tmp.push({
id: items.length,
type: info.type,
date: date,
time: time
});
setItems(tmp);
setReRender(!reRender);
}
return (
<MyTable
items = {itemArr}
></MyTable>
)
}
and my Child component:
export default function ScanTimer(props) {
console.log(props.data);
useEffect(() => {
console.log(props.data);
}, []);
return(
<div></div>
)
}
when I run my app, and add two item to the table, first console.log in child component (the one that is out of useEffect) shows right data. but last one (in useEffect) shows wrong data (the data that is for first item inserted into table).
it happens also when I init a state In this way:
const [data, setData] = useState(props.data);
in the Child element.
I don't know why it happens. can somebody help me??
first console.log in child component (the one that is out of useEffect) shows right data
That runs every time the component is rendered. It will always show the latest data.
but last one (in useEffect) shows wrong data (the data that is for first item inserted into table
The runs every time the dependency list changes.
So it runs on the first render (with the first value) because the dependencies have changed from "didn't exist" to "exists".
Then on subsequent renders, since there are no dependancies in the list (you passed an empty array), they haven't changed, so it doesn't run.
That is the point of useEffect.
If you want it to run when the data changes, you have to include that in the dependency list.
useEffect(() => {
console.log(props.data);
}, [props.data]);