2

I have an array of books in my redux store.

My reactjs component iterate over this like so (books.map=>(book=>{...renderbook})) to render the book.

So far so good.

Now when a new element is added to the books the entire list is being re-rendered. Is there a way in which this can be avoided? I believe 'ListView' does something similar in React-Native. Is there an equivalent in React-JS?

2

1 Answer 1

4

You need to specify the key property for each book:

books.map(book => <Book key={book.id} />);

If a book with an ID hasn't changed, they will not be re-rendered.

For more information on this, see: https://reactjs.org/docs/lists-and-keys.html

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

More info here as well: https://reactjs.org/docs/reconciliation.html#recursing-on-children

Sign up to request clarification or add additional context in comments.

3 Comments

@Aditya Your edit actually goes expressly against the docs: We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.
Ohh! I didn't knew that. Thank you for explaining, makes sense. What if there isn't any unique identifier?
Then you should attach one, or create one based on unique elements in the object (Like book.title+book.description)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.