• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

127
Views
React function stored in a state referring another is using the outdated value

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);

about 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error