Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - items in loop as an array data in state - rerendering items

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.

like image 586
juliancwirko Avatar asked Aug 15 '26 23:08

juliancwirko


1 Answers

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.

like image 141
David L. Walsh Avatar answered Aug 18 '26 13:08

David L. Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!