Search code examples
reactjslifecyclereact-lifecycle

ShouldComponentUpdate is set to false child components do not update if props change


My goal is to render a child component without re-rendering it's parent component.

So for example, App's state is passed as a prop straight to the Column component but Column is a child of Table and Table has ShouldComponentUpdate set to false (For example, table data didn't change..).

The problem.. if Apps state changes the Column component does not update.. unless ShouldComponentUpdate is set to true on the Table Component.. Is there anyway around this?

The documentation does say

Returning false does not prevent child components from re-rendering when their state changes.

But doesnt mention if their props change..

For test purposes I've created a demo here https://codesandbox.io/s/k2072rkp7o

Preview of the code:

const Column = ({ isSelected, onClick, children }) => (
  <div 
    style={{
      backgroundColor: isSelected ? 'green' : 'red',
      padding: '10px',
    }}
    onClick={onClick}
  >

    Column: {children}

  </div>
);

const Row = ({children }) => (
  <div 
    style={{
      backgroundColor: 'teal',
      padding: '10px'
    }}
  >

    Row {children}

  </div>
)


class Table extends React.Component {

  shouldComponentUpdate() {
    // There will be logic here to compare table data to see if its changed..
    return false
  }

  render() {

    return (
      <div 
        style={{
        backgroundColor: '#ccc',
        padding: '10px'
      }}>

      Table {this.props.children}

    </div>
    )
  }
}


class App extends React.Component {

  constructor() {
    super();
    this.state = {
      isSelected: false
    };
  }

  render() {

    return (
      <Table>

        <Row>
          <Column
            isSelected={this.state.isSelected}
            onClick={() => this.setState({
              isSelected: !this.state.isSelected
            })}
          />
        </Row>

      </Table>
    )
  }
}

Solution

  • Ok, after more reading, it's not possible... Which isn't good when you are playing with tables and want to apply a style to a cell component without causing a re-render of the whole table... Will have to look into alternatives...

    Heres the component lifecycle for anyone who has same problem..

    React Component lifecycle