0

As stated in the React docs, this API should be used sparingly because simpler alternatives can be used to achieve the same result. This is what I understand and totally agree with.
However, as a standalone API, there should be some scenario where it is mandatory. What puzzles me is that even the doc-mentioned "rare use cases" for this API is not convincing that it is exclusively needed.
Take for instance the second use case: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change
This lifecycle method is merely used to clear stale data before rendering the new props. But can't we just clear stale data in componentDidUpdate? Even though it will trigger an unnecessary re-render where the prop comparison will be equal, it is an acceptable solution for what it's worth.

 componentDidUpdate(prevProps, prevState) {
    if (prevProps.id !== this.props.id) {
      this.setState({ externalData: null });
      this._loadAsyncData(this.props.id);
    }
  }

And I tinkered a bit to show the two solutions yield the same end result: https://codesandbox.io/embed/sharp-paper-p5hv2?fontsize=14&hidenavigation=1&theme=dark

Where do you think is appropriate to use this API?

Zhengquan Bai
  • 1,057
  • 3
  • 14
  • 31

2 Answers2

0

But can't we just clear stale data in componentDidUpdate? Even though it will trigger an unnecessary re-render where the prop comparison will be equal, it is an acceptable solution for what it's worth.

If it's acceptable to render empty content then you don't need it.

I would rerender with loading indicator (by changing flag in state) beside existing content (not clearing existing data until load new) - if content is rendered as separate component (with passed the same props, "Presentational vs Container Components") rerendering is cheap.

xadm
  • 8,219
  • 3
  • 14
  • 25
0

Now I'm certain that componentDidUpdate can surely do the trick. The downside is no more than the extra unnecessary render pass and the ending condition you have to care about in componentDidUpdate in order not to trigger endless rendering cycle. But it's worth avoiding this unnecessary render by using getDerivedStateFromProps.

Zhengquan Bai
  • 1,057
  • 3
  • 14
  • 31