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

107
Vistas
Cannot access React props in state

I'm passing some data from parent to children like the following

<Children title={title}/>

Inside the children I have a state like this :

const [state,setState] = useState(title ? title : '')

Problem is, when accessing the title directly like this {title} it's working, accessing state on the other hand does not work. Should I useEffect for this to get data from parent when the state is loaded ?

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

0

You need to use useEffect hook here. because useState is basically used to initialize the value and not to update.

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

Because the problem with your approach is that when you do -

const [state,setState] = useState(title ? title : '')

This will set your state variable to ''(empty string) because on the initial render of your child component there is no guarantee that you are going to get the value of title. And when you get the value of title in your props. useState will not detect it.
So therefore to detect a change in your props and to setState based on updated props its recommended to use useEffect.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Access the props in the children component like this -

function childComponent(props) {
  //props.title -- access it in your component.
}

But what you're trying in your code is not recommended, you can't mutate the state of props. Read React docs

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is the correct implementation of this;

<ClassA title = "class a"/>



function ClassA(props){
// access the title by calling props.title
}
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