Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect each element of array individually by using react redux

The current approach is to connect whole book list into Book List Component. However, it is not an efficient to render huge components by changing only several fields in state. I dont know how to map each book component connect to each individual Book state.

The project is using redux. The application global state like this

{
  "books": [
    {
      "field1": "field1",
      "field2": "field2",
      "field3": "field3",
    } ...
  ]
}

In the Book List component, we connect list with it by using react redux

export default connect(state => ({
  books: state.books
}))(BookListComponent);

Now the requirement changes, fields in book will not be changed frequently. The issue is, if one field is changed, it will update the whole BookListComponent. That is not performant component I am expecting.

I would like to push connect logic down to individual Book Component in order to use reselect

The state doesnt have index of the book, I dont know how to write connect to make it work

export default connect(state => ({
  books[index]: state.books[index]
}))(BookListComponent);

Thanks for advance and all options are welcome

like image 205
Xiaohe Dong Avatar asked Oct 17 '22 16:10

Xiaohe Dong


1 Answers

Your second example is almost correct. A mapState function can be declared to take two parameters instead of one. If two parameters are declared, Redux will call that mapState function with the props that were given to the wrapper component. So, the mapState function for a list item would be:

const mapState = (state, ownProps) => {
    const book = state.books[ownProps.index];
    return {book}
}

My blog post Practical Redux, Part 6: Connected Lists, Forms, and Performance shows some examples of how to do that, and also discusses the key considerations for application performance in Redux.

like image 79
markerikson Avatar answered Oct 21 '22 00:10

markerikson