2
votes

I'm working on a redux/react app. We started with very few "connected" components (ie, components that access the redux state and dispatch actions directly). This resulted in every component passing down way too many props to all their children, and subchildren, etc, and the top-level "connected" components becoming god classes.

So, we're making many more components connected, and able to directly access redux state and dispatch actions via mapStateToProps and mapDispatchToProps. It's much nicer, and recommended by Dan Abramov here: https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.lye71jwmx

My question is, is it OK for a child component to fetch data from the state tree, assuming it's parent has sent the action which made the actual API call to get that data into the state tree?

To give a concrete example, using the classic "blog" app:

A <blog id=123/> component will render a blog post. It will make an API call that, in one hit, fetches the blog and it's nested comments as JSON.

That component will render a <comments blog_id=123 /> component. Is it OK for that child component to just assume that the parent has taken care of the API call to fetch the blog and it's nested comments, and therefore just fetch the comments from the state tree, and gracefully render nothing if the data doesn't exist yet (ie, the API call is still in progress)?

If not, what's the alternative here?

I understand in this contrived example, you'd probably just pass comments down as props. But in my real life example, it's much more complex.

So the question is, is it bad practice for a component to say "I'll render stuff from the state tree - but whoever uses me must make the API call in order for me to work properly"

1
Of course that's OK. That's how I'd approach it. The child component will won't render anything until the appropriate props are passed to it or state connected to it. You can pass this down to this child or fetch it from the Redux state tree, what ever works in your case. - KA01
Thanks. I thought so, but just wanted to make sure. Add that as an answer and I'll happily accept. - joshua.paling

1 Answers

1
votes

Of course that's OK. That's how I'd approach it.

With your example the child component won't render anything until the appropriate props are passed to it or state connected to it. You can pass this down to this child or fetch it from the Redux state tree, what ever works in your case.

If there are many child components or the target child is deep within the children I usually try to avoid passing down props. It's probably ideal and less cumbersome to fetch it's props from the state tree over passing state from child down to child and so on.

Take advantage of the mapStateToProps function to only pass defined props and allow the component to render what it's been given.