How does React State Actually Work?
How does React handle updates ?
How React Communicates With the Renderer ?
the renderer that handles the updates
setState calls renderer
The Update
- When we call setState, React adds the passed data to a queue.
- The updates are later handled one by one, but the changes are all applied at the same time.
React updates are closely related to React Fiber.
☘️ All of the updates are processed in two phases.
- During the first(render) phase, React calculates the new state and creates a list of effects.(those effects will handled during the second phase)
- Effect = activity like DOM mutation or Lifecycle method call
- 🚨 The first phase is asynchronous and doesn't result into anything visible to the user
- 🚨 During the second phase, effects are applied and the second phase is synchronous
However, most lifecycle methods are actually called in the first phase
state getDerivedStateFromProps(props, state) { console.log("getDerivedStateFromProps"); return state; } shouldComponentUpdate(nextProps, nextState) { console.log("shouldComponentUpdate") return true; } componentDidUpdate(prevProps, prevState, snapshot) { console.log("componentDidUpdate") } render() { console.log("render") return ( <button onClick={() => this.setState(() => ({text: 'I have been updated'})}> {this.state.text} </button> ) } // ======= output ======= getDerivedStateFromProps shouldComponentUpdate render componentDidUpdate
getDerivedStateFromProps = call depend on state or props
- allow us to change state based on prop changes
It takes props and state as parameters and should return the correct and possibly adjusted state
Derived means modified, so the method name makes change
shouldComponentUpdate
By default, a React component re-renders on every state change
- allow us to prevent re-rendering
- exists solely as a performance optimization
Two phase
-
getDerivedStateFromProps and shouldComponentUpdate are called during the first (render) phase.
-
componentDidUpdate is called during the second (commit) phase
- perfect place for side effects
- DOM changes, subscriptions, network request
high level
- setState is called.
- data is added to a queue
- React starts handling the update
- new state is calculated + getDerivedStateFromProps is called
- shouldComponentUpdate is called with final (derived) state
- render is called
- DOM changeds are made
- componentDidUpdate is called
学而不思则罔,思而不学则殆!
分类:
React
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
2023-01-04 可视化Echart模板component