Potential `useSubscribe()` improvements: dependency array and fixing React compiler warnings

Abierto
#506 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
48/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
javascript, react

Línea de trabajo

Start by reading the existing useSubscribe() implementation and how it calls useTracker(); the issue does not name the source file or tests. Compare its behavior with the two proposed dependency-aware versions, especially how subscription readiness responds when name or args change. Done means the maintainers decide which improvement to make and add coverage for the chosen behavior and React compiler warnings.

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

Descripción

The problem

The regular import { useSuspense } from "meteor/react-meteor-data" works well in most cases. However, we had an overly complex (and likely buggy) component where the function returned by useSubscribe() always returned true even after the data clearly had loaded.

In normal cases, this is usually never a problem, but it did become a problem in our complex component which have excessive and inconsistent re-renders. Debugging the problem revealed that useSubscribe() seemingly doesn't track changes to name or args since it does not pass any dependency array to useTracker().

In our case, this led to the component getting stuck 5/6 times and only making it through rendering 1/6 times.

What fixed it locally in our project

After replacing useSubscribe() with useSubscribeWithDeps() as shown below, it always works, despite being used in a buggy component.

I tracked down the problem and patched it locally. Now I wonder if some of the following suggestions would be valuable to submit as PRs?

  1. Does it make sense to add the dependency array to the core useSubscribe()?
  2. Alternatively, would this be better suited as a new hook useSubscribeWithDeps()?
  3. Bonus: The current useSubscribe() has several React compiler linting warnings because it mutates local variables potentially after rendering. Wrapping local state in refs solves this, while preserving the intended behavior.
Patched useSubscribeWithDeps()
/**
 * Alternative to `useSubscribe()` that also tracks dependencies.
 *
 * This ensures that conditional subscriptions work as expected by
 * rerunning the tracker when the `name` or `args` change.
 * 
 * Also fixes React compiler warnings by using refs instead of local variables.
 */
export function useSubscribeWithDeps(name?: string, ...args: any[]): () => boolean {
  const updateOnReady = useRef(false);
  const subscription = useRef<Meteor.SubscriptionHandle>(null);

  const isReady = useTracker(
    () => {
      if (!name) return true;

      subscription.current = Meteor.subscribe(name, ...args);

      return subscription.current.ready();
    },
    [name, EJSON.stringify(args as any)],
    () => !updateOnReady.current,
  );

  return () => {
    updateOnReady.current = true;
    return !isReady;
  };
}

Update

This version worked even more consistently in our app:

/**
 * Alternative to `useSubscribe()` that also tracks dependencies.
 *
 * This ensures that conditional subscriptions work as expected by
 * rerunning the tracker when the name or args change.
 */
export const useSubscribeWithDeps = (name?: string, ...args: any[]): (() => boolean) => {
  const isReady = useTracker(() => {
    if (!name) return true;
    return Meteor.subscribe(name, ...args).ready();
  }, [name, EJSON.stringify(args as any)]);

  return () => !isReady;
};
Lenguaje dominante
JavaScript
Estrellas
577
Forks
165
Merge medio
2 d 6 h
PR fusionados (30 d)
1

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

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.

Más de meteor/react-packages

Todos los issues de meteor/react-packages

Issues similares

Más issues de JavaScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.