I've a parent-child component structure, where parent fetches data to be displayed and child component displays the data. I want to update parent's state from child component. I'm sending a handler function from parent to the child as a prop, which is invoking the parent's handler function. Inside the parent's handler function, I'm updating state, however, that is not getting updated. Here is what I've done so far:
Parent Component:
const [startTime, setStartTime] = useState(new Date()); const myHandler = () => { const tn = new Date(); setStartTime(tn); console.log(tn, startTime); } return ( <ChildComponent myHandler={myHandler} /> ); Child Component:
interface Props { myHandler:(params: any) => any; } const someAction = useCallback( (studentId: Student['id']) => () => { navigation.push(STUDENTROUTE, { studentId }); myHandler(studentId); }, [navigation] ); As output Tue Sep 11 2022 10:59:42 GMT-0400 (Eastern Daylight Time) is the time at which the state was initialized, and on subsequent calls, it never gets updated. Following is the output in Chrome debugger:
Tue Sep 11 2022 10:59:47 GMT-0400 (Eastern Daylight Time) Tue Sep 11 2022 10:59:42 GMT-0400 (Eastern Daylight Time) Tue Sep 11 2022 11:00:06 GMT-0400 (Eastern Daylight Time) Tue Sep 11 2022 10:59:42 GMT-0400 (Eastern Daylight Time) What am I doing wrong here? Do I have to use useEffect() hook here to update the state? If yes, how can I use it in this scenario of child updating parent's state?