I need to pass a complicated object to its child, and such object will be modified by another component via the related setter function. That means I have to store the complicated object in a state. Let's call it complicatedState.
The object I am trying to store in state contains a function and referring another state, called simpleState. Both states are managed by component Debug. The desired behavior of it is to log the latest value of simpleState. The problem is, the function is always using the outdated value of simpleState, even if simpleState has been updated by button clicks.
I heard about useCallback which can subscribe changes of another variable. I tried but that doesn't work. Does anyone have any idea?
Besides, is storing function in state a ill-formed coding scheme?
const { useState } = React;
function Child(props) {
const { value } = props;
const { callback } = value;
return <>
<button onClick={() => {
callback();
}}>Test</button>
</>
}
function Debug() {
const [simpleState, setSimpleState] = useState(() => {
console.log('calling useState')
return { id: 9 }
})
const defaultValue = {
callback: () => {
console.log(simpleState);
},
// callback: useCallback(() => {
// console.log(simpleState)
// }, [simpleState])
}
const [complicatedState, setComplicatedState] = useState(defaultValue);
return <>
<Child value={complicatedState} />
{/* <AnotherComponent onChange={setComplicatedState}> */}
<button onClick={() => {
const updated = { id: simpleState.id + 1 };
console.log(`outdated: ${JSON.stringify(simpleState)} ==> updated: ${JSON.stringify(updated)}`)
setSimpleState(updated)
}}>+</button>
</>
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Debug />, rootElement);