reactjs / reactjs/react.dev

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

Ouverte
#5,379 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Langage dominant
JavaScript
Étoiles
11.8k
Forks
7.9k
Merge moyen
1 j 11 h
PR mergées (30 j)
11

Description

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

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez par la page Keeping Components Pure, en particulier par le défi « Fix a broken clock » et son exemple avec useState, puis examinez l’issue associée #5136. Déterminez si l’explication distingue suffisamment un initialiseur d’état d’un effet secondaire pendant le rendu, et mettez à jour la documentation afin que la source de l’heure initiale et la règle de pureté soient sans ambiguïté.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
javascript, react
Domaine
documentation
Type d'issue
Documentation
Difficulté
3/5
Temps estimé
1-2 jours
Activité
À l'abandon
Clarté
À clarifier
Accessibilité débutants
30/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.