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.

☘️ 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

  1. getDerivedStateFromProps and shouldComponentUpdate are called during the first (render) phase.

  2. componentDidUpdate is called during the second (commit) phase

  • perfect place for side effects
  • DOM changes, subscriptions, network request
high level
  1. setState is called.
  2. data is added to a queue
  3. React starts handling the update
  4. new state is calculated + getDerivedStateFromProps is called
  5. shouldComponentUpdate is called with final (derived) state
  6. render is called
  7. DOM changeds are made
  8. componentDidUpdate is called
posted @   Felix_Openmind  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
历史上的今天:
2023-01-04 可视化Echart模板component
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}
点击右上角即可分享
微信分享提示