Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda