Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
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 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!