As3Script
As3Script

Reputation: 147

Where to compute derived data in React-redux application

I am working with an application where I have to compute derived data before render.

Background: Usually, I get the data(from API using mapStateToProps) in my component and perform all the manipulation inside the component.

Once I received data from API I have to map them. And don´t need to map again and again until there is no further API call.

So, Is what is the place to manipulate data if that is not needed until next API call?.

Thanks in advance

Upvotes: 0

Views: 2256

Answers (2)

Andrei R
Andrei R

Reputation: 5168

From your question it sounds like you want to transform your data before you store it in Redux state - just after you get it from the API. It's hard to advise without seeing your code structure. You could await on the api call in the action and transform it into the right shape before handing off to a reducer to store in state.

Upvotes: 0

banna
banna

Reputation: 249

In Redux the functions that are responsible in computing derived data are called "selectors". As said in Redux documentation:

It's generally suggested that selectors are defined alongside reducers and exported, and then reused elsewhere (such as in mapStateToProps functions, in async action creators, or sagas) to colocate all the code that knows about the actual shape of the state tree in the reducer files.

Calling these function whenever any state changes isn't a good idea when it comes to performance. There is a library called reselect that can memoize (cache) the computed state value for a selector input and returns that same cached state if the same selector inputs are passed again. So basically inputs are tracked and if the same input repeats their cached state is returned again without any recomputation.

See use cases and examples for reselect here, though I'd recommend against using reselect until your app begin to have performance issues.

Upvotes: 3

Related Questions