Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!