The Deprecated componentWillReceiveProps

· 2 min read

React v16.3+ has marked componentWillReceiveProps as deprecated, and version 17 will remove it completely. So why is this lifecycle method being deprecated, what are its drawbacks, and how should we handle the same requirements with the new approach? This article will help me organize this function.

When componentWillReceiveProps Triggers

As the name suggests, it triggers when props change, but in reality, it also triggers even when props don’t change. When a parent component re-renders, the child component’s componentWillReceiveProps will trigger. So, componentWillReceiveProps doesn't only trigger when props actually change.

Using componentWillReceiveProps

  1. Sometimes our state depends on props, so we might execute setState at this time. But note that setState is an asynchronous operation, and state changes will also trigger a new render.
  2. If side effects are executed in componentWillReceiveProps, there’s a risk of memory overflow. For example, initiating async actions, updating Redux state data, which then triggers component props updates, creating a loop that continuously triggers componentWillReceiveProps.

Based on these problems, the official team deprecated this function. So how should we handle these requirements now?

How We Should Approach It

  1. If state updates depend on props, we can use the new static function getDerivedStateFromProps
  2. If it’s a side effect, it should be executed in didUpdate, didMount, and user interaction operations

Avoiding the Use of This Deprecated Method in Projects

We can configure appropriate lint rules to ensure this type of code doesn’t exist, which also reduces the rewriting costs that future framework upgrades might bring.

yarn add eslint-plugin-react -d

For detailed information, click here

Final Thoughts

What we’re discussing here is React. Compared to Angular, in Angular when a parent component renders and updates, the child component’s change method doesn’t re-trigger. So, different frameworks have quite significant differences in these basic hooks.

References