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

306
Vistas
React: stale props in child component

Here is the CodeSandBox link: https://codesandbox.io/s/stale-prop-one-g92sv?file=/src/App.js

I find the child components will not show the correct counter values after two button clicks, though the counter is actually incrementing:

import "./styles.css";
import { useState } from "react";

const MyComponent = ({ value }) => {
  const [counter] = useState(value);
  return <span>{counter}</span>;
};

export default function App() {
  const [counter, setCounter] = useState(0);
  const isVisible = counter !== 1;
  console.log(counter);
  return (
    <div className="App">
      <div>
        <button onClick={() => setCounter((counter) => counter + 1)}>
          Click me
        </button>
      </div>
      {isVisible && (
        <div>
          Message 1 is: <MyComponent value={counter} />
        </div>
      )}
      <div style={isVisible ? { display: "block" } : { display: "none" }}>
        Message 2 is: <MyComponent value={counter} />
      </div>
    </div>
  );
}

I try to force child component re-render by assigning counter to its key:

export default function App() {
  const [counter, setCounter] = useState(0);
  const isVisible = counter !== 1;
  console.log(counter);
  return (
    <div className="App">
      <div>
        <button onClick={() => setCounter((counter) => counter + 1)}>
          Click me
        </button>
      </div>
      {isVisible && (
        <div>
          Message 1 is: <MyComponent  key = {counter} value={counter} />
        </div>
      )}
      <div style={isVisible ? { display: "block" } : { display: "none" }}>
        Message 2 is: <MyComponent key = {counter} value={counter} />
      </div>
    </div>
  );
}

It works, but I still have no idea why the previous one does not work, since the props.value in MyComponent has changed... Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

With this:

const MyComponent = ({ value }) => {
  const [counter] = useState(value);
  return <span>{counter}</span>;
};

You're telling React to set the initial state to the first value prop passed to the component, on mount.

When the component re-renders, the component has already been mounted, so the value passed to useState is ignored - instead, the counter in that child is taken from the state of MyComponent - which is equal to the initial state in MyComponent, the initial value prop passed.

For what you're trying to do, you only have a single value throughout the app here that you want to use everywhere, so you should only have one useState call, in the parent - and then render the counter in the child from the prop, which will change with the parent state.

const MyComponent = ({ value }) => {
  return <span>{value}</span>;
};
about 4 years ago · Juan Pablo Isaza Denunciar
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