Too much state at the top? (beginner question)


(JW) #1

I’m learning React by creating a multi-tabbed app, which uses React Router 4. I want each tab to maintain its contents even when you switch away, similar to the iOS App Store.

Since the router removes a component when it’s not in the current route, I can’t store any state in my tab components, or it will get lost when you switch away. So, having taken Thinking in React to heart, I’ve pretty much moved all my state up to the top-level App component.

But as a result, my App component is way too complex. For example, each tab loads some data over the net. So for each tab, my App component has state fields for the data, the loading/loaded state of the data, its sort direction/order, its filters, etc. Plus it’s got event-handler functions to load, sort, filter, add, update, and delete data, which it passes down to the lower-level components within the tab.

Is this a common problem? How do I simplify things? I’ve avoided adding Redux because of articles like this, and since this seems like a pretty simple app. Any advice would be appreciated…let me know if this isn’t the appropriate forum.


(Joe Dodd) #2

It might help to see just how complex your App component is via your code. From what you’ve described, it doesn’t sound too complex to me. But others may have different opinions.


(JW) #3

I can’t really post it here, but it’s definitely starting to get bigger than any sensible class should be. I’m working on factoring out some things into separate classes.

But the main problem I run into is that the App component still needs to have access to all the state. So if I move code into a separate class, it needs to call back to the App component somehow to get/set the state. This seems ugly. If all my setState and this.state calls need to happen in App, it kind of limits what kind of logic I can move into other classes.

The other problem is that the App also needs access all the event-handler callbacks, to pass on to its child components. These seem a little easier to factor out, since I can put them in separate classes and just refer to them from App.