reactjs / reactjs/react.dev

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

Aperta
#5,379 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
JavaScript
Stelle
11.8k
Fork
7.9k
Merge medio
1g 11h
PR unite (30g)
11

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dalla pagina Keeping Components Pure, in particolare dalla sfida «Fix a broken clock» e dal relativo esempio con useState, quindi esamina l’issue correlata #5136. Chiarisci se la spiegazione distingue adeguatamente un inizializzatore dello stato da un effetto collaterale durante il rendering e aggiorna la documentazione in modo che la fonte dell’ora iniziale e la regola di purezza siano inequivocabili.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
javascript, react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
30/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.