Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda