In this simple example, I am memoizing Child component using useMemo and passing callback back to parent function to add data to react hook array, which is initially set as empty.
My question is as follows: Why hook data never changes and keeps it's initial state in callback function that comes from Child component which is memoized. However, when checking data hook in useEffect method or using that hook in rendering - it always has the newest state.
It is more of a general question what happens behind the hood and what is the best way, for example, to check against duplicate values in callback functions from memoized child components if data always has initial state.
I am aware of useReducer and that I can manipulate data in hooks setter method before adding it, but maybe there are other methods?
Parent component:
import React, {useEffect, useState} from 'react';
import Child from "./Child";
function App() {
const [data, setData] = useState([]);
useEffect(()=>{
console.log("UseEffect", data)
},[data]);
return (
<div>
<Child callback={(val)=>{
console.log("Always returns initial state", data); // <----------Why?
setData(old=>{
console.log("Return previous state", old);
return [...old, val]
})
}} />
Length: {data.length /*Always gets updated*/}
</div>
);
}
export default App;
Child component: In real scenario it is a map, that I want to render only once, without causing re-renders.
import React, {useMemo} from "react"
export default function Child({callback}) {
return useMemo(()=>{
return <button onClick={()=>callback(1)}>
Press!
</button>
},[])
}
data
as props and use it in your second argument of useMemo. – Bhojendra Rauniyar