reactjs / reactjs/react.dev

Questions about components purity and "Fix a broken clock" challenge

未關閉
#5,379 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
JavaScript
星號
11.8k
分支
7.9k
平均合併
1 天 11 小時
30 天內合併 PR
11

描述

Reading page Keeping Components Pure made many things clear to me that I somehow already knew but could not put into words before. However, in my opinion Challenge 1 Fix a broken clock raises more questions than it tries to answer.

If x = 3, y won’t sometimes be 9 or –1 or 2.5 depending on the time of day or the state of the stock market.

I understand that the Clock component is considered to be pure because the current time is passed as a prop and time.getHours() will always return the same hour based on that prop:

export default function Clock({ time }) {
  let hours = time.getHours();
  // ...
}

The docs make clear that calling new Date() during render would make the component impure. Also I am assuming that all components must be pure, even the root component. So I was asking where and how should new Date() be called to access the current time? The docs say:

[...] in React there are three kinds of inputs that you can read while rendering: props, state, and context.

and

When you need to “change things”, you’ll usually want to do it in an event handler. As a last resort, you can useEffect.

I am able to look into the code of App.js when forking the CodeSandbox:

import { useState, useEffect } from 'react';
import Clock from './Clock.js';

function useTime() {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => {
      setTime(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return time;
}

export default function App() {
  const time = useTime();
  return (
    <Clock time={time} />
  );
}

I am assuming that also custom hooks have to be pure. I also understand that calling setTime(new Date()) in a useEffect plays by the rules of purity.

Now, what is not clear to me is, how setting the initial value const [time, setTime] = useState(() => new Date()) ensures that the component is pure? As far as I know this will happen during (first) render. So isn't this a side effect called during render? Is this some kind of exception to the rules?

Note that there is another related issue to this challenge: https://github.com/reactjs/reactjs.org/issues/5136

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先從 Keeping Components Pure 頁面開始,尤其是「Fix a broken clock」挑戰及其中的 useState 範例,然後查看相關 issue #5136。釐清說明是否充分區分了 state initializer 與 render 期間的副作用,並更新文件,讓初始時間的來源和純函式規則都明確無歧義。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
javascript, react
領域
documentation
Issue 類型
文件
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
需要釐清
新手友好度
30/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。