The Deprecated componentWillReceiveProps

This article introduces the deprecated componentWillReceiveProps, including usage scenarios and implementation details, to improve efficiency in understanding the deprecated componentWillReceiveProps.

Jun 15, 2020 · 2 min read · 295 Words · -Views -Comments · Programming
React 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover