3

In React I have problem with rerenders of the items components in loop. I have one main component with state like:

this.state = {
    data: [{...}, {...}, {...}]
}

I iterate this data:

render() {
        const elems = this.state.data.map(item => {
        let id = randomId();
        return (
            <ItemComponent
                key={id}
                id={id} (...other props) />
        )
    });
    return (
        <div>
            {elems}
        </div>
    );
}

The component has special CSS classes with animations so if the component is rendered it is animated (small animations) and all works well, but when I add something to the state (another 'data' array object item) all items are rerendered so all starts to animate. I want just the new one to be animated. This is a problem with rerendering all items. The old ones shouldn't be rendered when the new appears in the data array. I am sure that there is something basic which I am missing here. I know that there is shouldComponentUpdate and I tried to use it in my ItemComponent but it just do nothing there, even when I set up it to return false :/

What could I do with this? I just don't want to rerender items which don't change and are just rendered. I just want to add new object to the data array trigger state change and render just the added object not all items again. I tought that React can manage it internally. Or maybe there is a way to use shouldComponentUpdate in my ItemComponent?

I add new items by:

newArray = this.state.data.slice();
newArray.push({...});
this.setState({data: newArray});

Thanks in advance.

1 Answer 1

4

The problem is your key. In React, the key uniquely identifies the component. But your key is randomly generated on every render. That's why React treats every item as a new component on each render.

You need to either come up with a more predictable key, or ensure the random key is only generated once per item.

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

2 Comments

I had same question ^^, so if in loop rendering there will be not random keys, and we change only one element from data it rerenders only this specific element itself? or should we add some additional code to achieve that? thank you !
Yes the point of keys is to prevent unnecessary re-renders. See the docs here: reactjs.org/docs/lists-and-keys.html If you have any other questions, please start a new post.

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.