1

I read somewhere that it's good practice or common to have the state in the parent most component, but the parent most component is App, right? Well there may be some cases where you don't need to have the state in the App component. I'm wondering if having the state in App component is a good idea or something that React developers usually do.

I ask this because in the app that I'm currently building I might need to lift the state up to the parent most component (App) to be able to pass data to all children. BUT, doing so means that I will also need to go 2 levels of nesting, for example:

class App extendes Component {
 render() {
 <React.Fragment>
  <main className="container">
    <FirstLevel data={this.state.mainData} moreData={this.state.moreData} />
  </main>
</React.Fragment>
 }
}

And the FirstLevel component has another component that also needs data from state:

const FirstLevel = props => {
 return (
  <div>
   <p>This is first level child</p>
    <SecondLevel moreData={this.props.moreData} />
  </div>
 );
}

It's easy to see why things can get messy here, I use Sass and I know we shouldn't go beyond 3 level of nesting. I'd like to know what level of nesting would be considered bad practice in React or if the example above is fine but I shouldn't nest deeper than that.

Gilbert R.
  • 282
  • 1
  • 7
  • 19

1 Answers1

1

It's not recommended to pass props after one level nesting. There are libraries like Redux, Mobx. I personally use Redux as you can manage your complete app state globally without even worrying about hiearchy of component. The latest react Context API is already there to tackle prop drilling issue by providing Provider and Consumer concept.

Sakhi Mansoor
  • 7,832
  • 5
  • 22
  • 37
  • Umm I see... I don't know anything about Redux yet as I want to feel more comfortable with React before jumping to Redux but I already see people use this library a lot. – Gilbert R. Oct 28 '18 at 18:31
  • 1
    use Context API with less boiler plate. You could use it efficiently to avoid prop drilling problem – Sakhi Mansoor Oct 28 '18 at 18:32