reactjs / reactjs/react.dev

[Suggestion]: Adding an Explanation Text to Optimizing Re-renders in useContext Section

Abierto
#6,599 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Summary

Add an explanation text to prevent missunderstanding of usage useContext with useMemo.

Page

https://react.dev/reference/react/useContext#optimizing-re-renders-when-passing-objects-and-functions

Details

I think it would be helpful to have an explanation text in the section below.

Optimizing re-renders when passing objects and functions
https://react.dev/reference/react/useContext#optimizing-re-renders-when-passing-objects-and-functions

import { useCallback, useMemo } from 'react';

function MyApp() {
  const [currentUser, setCurrentUser] = useState(null);

  const login = useCallback((response) => {
    storeCredentials(response.credentials);
    setCurrentUser(response.user);
  }, []);

  const contextValue = useMemo(() => ({
    currentUser,
    login
  }), [currentUser, login]);

  return (
    <AuthContext.Provider value={contextValue}>
      <Page />
    </AuthContext.Provider>
  );
}

In this section, the currentUser type is not certain. But, the user type is an object in general usages. So, when using useMemo with an object dependency, it relies on object reference changes rather than the equality of object values. If the object reference remains the same, even if the internal values are the same, useMemo may not provide the expected optimization.

Even though the currentUser object has the same values, the reference remains the same, and useMemo will recalculate the memoized value because it's based on the change in reference.

Note: Avoid using complex data types, especially objects, directly in the dependency array of useMemo.
When using objects, JavaScript relies on object reference changes, not values.
If the object reference remains the same, useMemo might not optimize as expected.
To ensure proper memoization, consider using primitive values or ensuring object immutability.
For example, prefer setCurrentUser({ ...currentUser, updatedProperty: "newValue" }) over modifying the existing object directly using login function.

Maybe adding text like above would be helpful.

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 por la sección “Optimizing re-renders when passing objects and functions” de la página de referencia de useContext y revisa la explicación circundante sobre las dependencias de useMemo. Verifica la aclaración propuesta según el comportamiento de las referencias a objetos en JavaScript y, después, actualiza la documentación para que el comportamiento de memoización del ejemplo y las actualizaciones inmutables no sean ambiguos.

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
2/5
Tiempo estimado
1-3 horas
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.