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

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
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