cgold
cgold

Reputation: 4245

React updating state for child components

My app is structured as follows:

<App>
    <SelectItems/>
    <Tabs>
        <Tab> <Window1> </Tab>
        <Tab> <Window2> </Tab>
    </Tabs>
</App>

The App has a state element called allItems, and SelectItems is used to narrow this down to App.state.selectedItems. The tabs work in a way that only one of the tabs shows at a given time, it's a component from React-Bootstrap.

The Window1 and Window2 display data that depend on the selectedItems, the data (let's call it data1 and data2) is obtained via a computationally intensive api call. Here's the problem. The cleanest way to do this while thinking in React is to "pull the state up", so that data1 and data2 are updated from App whenever the selectedItems change, and the data is then stored in the state of App and passed down to the tabs. This however is inefficient, because only one Window is showing at a given time, so I'm wasting time updating data that I'm never showing. In my actual app I've got many tabs, so it's a real problem.

What's a way of fixing this? I want the Windows to update whenever the App.state.selection changes, and I looked at static getDerivedStateFromProps(props, state) but it looks like (but I'm not sure) that this function won't work because the state updating would be asynchronous, as it requires an API call.

Are there general strategies one can use in this situation?

Thanks!

Upvotes: 1

Views: 43

Answers (1)

cdimitroulas
cdimitroulas

Reputation: 2549

You have a couple of options, the first one is the one most people would recommend (because it is a popular option) and that is to use Redux to manage your application state.

Redux will allow you to keep all your data in a separate "store". Then from your components you can connect to the store and access the data which is relevant to them. Those components should only update when the data they are interested in is changed, any other changes to the store will be ignored. There are a lot of good tutorials on using Redux and React together which you can find online - apparently the ones on egghead are pretty good, you can maybe try this one to get started.

Your other option might be to use a PureComponent so that you can limit when your component will re-render to only when it's props or state change rather than if the parent re-renders. You can read about this here. It's actually similar to the previous solution are the connect function provided by the react-redux library to connect to the Redux store wraps your component in a PureComponent.

Upvotes: 1

Related Questions