8

Very basic code sample of a list:

class List extends React.Component {
    render() {
        const listComponent = this.props.numbers.map((number) =>
            <Item key={ number.toString() } value={ number } />,
        );

        return (
            <div>
                <button onClick={ () => this.setState({ test: 1 })}>Re-render list</button>
                { listComponent }
            </div>
        );
    }
}

An here is the item:

class Item extends React.Component {
    render() {
        return (
            <div>{ this.props.value + ', rendered time:' + new Date().getTime() }</div>
        );
    }
}

When I click the button, the state is updated so the List component is re-rendered.

However, if my understanding is correct, the items should not be re-rendered since the key item has not changed. But it does re-render since the timestamp is updated.

Can someone explain me why?

vital
  • 1,308
  • 3
  • 13
  • 28

3 Answers3

11

Your understanding is completely wrong

The whole purpose of key, is for ordering rather than rendering. Image you have items a,b,c,d and reorder them by switch a and c, i.e. c,b,a,d. Without the key, it is extremely hard for react to figure out how to transform from the old virtual DOM to new virtual DOM.

Please read this https://facebook.github.io/react/docs/lists-and-keys.html

Guichi
  • 2,150
  • 1
  • 19
  • 27
2

By re-rendering a component you also start a chain reaction re-render on all the child components.

If you wish to prevent a child component to re-render (if some of the passed props didn't change for example) you can use the lifecycle method shouldComponentUpdate().

class Item extends React.Component {
    shouldComponentUpdate(nextProps) {
        // only re-render if props.value has changed
        return this.props.value !== nextProps.value;
    }

    render() {
        return (
            <div>{ this.props.value + ', rendered time:' + new Date().getTime() }</div>
        );
    }
}
Tom Van Rompaey
  • 3,556
  • 20
  • 22
  • I understand that, but then what's the point of having a key properties for items of an array? – vital Jul 28 '17 at 04:17
  • 1
    How I understand it, these keys are just a performance optimization for comparing if anything has changed on the list items. Nothing to do with re-render or not re-render. Here's an in-depth explanation about why keys are necessary: https://facebook.github.io/react/docs/reconciliation.html#recursing-on-children – Tom Van Rompaey Jul 28 '17 at 05:06
0

Whenever your state changes, the whole component will be re-rendered by React. It's defaulted to true if you haven't set the shouldComponentUpdate() function to return false. Have a look at React's component lifecycle.

kotAPI
  • 387
  • 1
  • 7
  • 20