Preact: 10.0.0-alpha.0: shouldComponentUpdate blocks updating component as well as render.

Created on 6 Mar 2019  路  3Comments  路  Source: preactjs/preact

Example:
props is not updated permanently while shouldComponentUpdate returns false

import { render, Component } from "preact";

class A extends Component {
  state = { a: 0 };
  componentDidMount() {
    this.setState({ a: 1 }); // update props
  }
  render() {
    return <B a={this.state.a} />;
  }
}

class B extends Component {
  state = { now: "---" };
  timer = 0;
  updateState = () => {
    this.setState({ now: new Date().toString() });
  };
  componentDidMount() {
    this.timer = setInterval(this.updateState, 1000);
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (nextProps !== this.props) {
      console.log(
        "called infinitely!! it must be called only once.",
        new Date(),
        nextProps.a,
        this.props.a
      );
      // nothing do when props changed
      return false;
    }
    return true;
  }
  render() {
    return (
      <p>
        {this.state.now}, {this.props.a}
      </p>
    );
  }
}

render(<A />, document.getElementById("root"));

https://codesandbox.io/s/o57vp43o3q


refs:
https://github.com/developit/preact/blob/753d8849997612f2fa3d168a28ff4dfba65b39bc/src/diff/index.js#L103-L106

bug

Most helpful comment

Looks like the props reference just needs to be updated in the sCU:false codepath.

All 3 comments

Looks like the props reference just needs to be updated in the sCU:false codepath.

note: This behavior is sometimes used to compute props.

// this causes an infinite loop
shouldComponentUpdate(nextProps, nextState) {
  if (nextProps !== this.props) {
    this.setState(recomputeProps(nextProps));
    return false;
  }
  return true;
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

matuscongrady picture matuscongrady  路  3Comments

paulkatich picture paulkatich  路  3Comments

skaraman picture skaraman  路  3Comments

nopantsmonkey picture nopantsmonkey  路  3Comments

matthewmueller picture matthewmueller  路  3Comments