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

65
Vistas
React useState with state that updates based on props

I have a functional React component that roughly looks like this:

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)  

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}

This obviously doesn't work because React only computes the initial state part once, so myState isn't updated on prop1 change.

Is there a way to make this work without using useReducer? Is this a good use case for useEffect?

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

0

This is because state is only initialized once. That's why the second value returned from useState() is a setter function. It's intended to be the only way to update the state after initialization. In this case you would use a useEffect() hook to update the state when props change (although there's not generally a great reason to initialize state with a prop).

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)

  useEffect(() => {
    setState(prop1)
  }, [prop1])

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

To update myState on prop1 change, pass a second argument to useEffect that is the array of values that the effect depends on.

An example looks like this:

const MyComponent = ({ prop1 }) => {
  const [myState, setState] = useState(prop1);

  useEffect(() => {
    setState(prop1);
  }, [prop1]);

  return (
    <>
      {myState && <div>Some text...</div>}
      <div onClick={() => setState(true)}>Click me</div>
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

useState(initialValue) will only use initialValue on the first render and does not change after re-renders. So you need to write your code like this:

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)

  useEffect(() => {
    setState(prop1)
  }, [prop1])

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}
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