[React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3
The componentWillReceiveProps() method is being deprecated in future version of React (17). Many of us use this method day-to-day to check for incoming prop changes, store state, and to invoke side effects like logging or fetching data from a server.
In this lesson, we'll look at how to refactor an existing component that uses componentWillReceiveProps() to instead use getDerivedStateFromProps() and componentDidUpdate().
Additional Resources: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles
In short,
componentWillReceiveProps:
The new static
getDerivedStateFromProps
lifecycle is invoked after a component is instantiated as well as when it receives new props. It can return an object to updatestate
, ornull
to indicate that the newprops
do not require anystate
updates.
should handle any local data changes:
static getDerivedStateFromProps(nextProps, prevState) { const { number } = nextProps; return number === prevState.number ? { computedMessage: "Same number, try again!", number } : { computedMessage: null, number }; }
componentDidUpdate:
hanlde any async update
componentDidUpdate(nextProps) { const { number } = nextProps; if (this.state.computedMessage === null) { fakeServerRequest(this.props.number).then(result => { this.setState({ computedMessage: result }); }); } }
componentWillReceiveProps together with
componentDidUpdate
, this new lifecycle should cover all use cases for the legacycomponentWillReceiveProps
.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-05-02 [SCSS] Reuse Styles with the SCSS @extend Directive
2017-05-02 [Node.js] Create a model to persist data in a Node.js LoopBack API
2016-05-02 [Flexbox] Using flex-direction to layout content horizontally and vertically
2016-05-02 [AngularJS] Design Pattern: Simple Mediator
2016-05-02 [Core Javascirpt] Basic Metaprogramming: Dynamic Method