reactjs / reactjs/react.dev

Questionable Comment in the `useEvent` Example

Abierto
#5,280 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
JavaScript
Estrellas
11.8k
Forks
7.9k
Merge medio
1 d 11 h
PR fusionados (30 d)
11

Descripción

I found a paragraph from Separating Events from Effects in the beta React Docs, which I couldn't wrap my head around:

In this example, url inside onVisit corresponds to the latest url (which could have already changed), but visitedUrl corresponds to the url that originally caused this Effect (and this onVisit call) to run.

The mentioned example is effectively the one below:

function Page({ url }) {
  const { items } = useContext(ShoppingCartContext);
  const numberOfItems = items.length;

  const onVisit = useEvent(visitedUrl => {
    // `url` captured here is claimed to be the latest, not the original
    // but what about `numberOfItems`?
    logVisit(visitedUrl, numberOfItems);
  });

  // intend to log the `url` that originally caused this Effect, 
  // along with the original `numberOfItems`.
  useEffect(() => {
    setTimeout(() => {
      onVisit(url);
    }, 5000); // Delay logging visits
  }, [url]);

  // ...
}

More essentially, I believe my confusion stems from the claims below:

This solves the problem. Similar to the set functions returned from useState, all Event functions are stable: they never change on a re-render. This is why you can skip them in the dependency list. They are not reactive.

How can Event functions like onVisit are stable, when they need to capture the relevant reactive values like numberOfItems?

Are they stable, but have access to the freshly-constructed anonymous function, which captures the relevant reactive values?

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con el ejemplo “Separating Events from Effects” enlazado en el issue y compara las afirmaciones sobre la estabilidad de useEvent con los valores mostrados numberOfItems y url. Se considera terminado cuando la documentación aclara claramente qué valores observa el callback retrasado y explica por qué la función de evento puede omitirse de las dependencias.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
javascript, react
Área
documentation
Tipo de issue
Documentación
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.