reactjs / reactjs/react.dev

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

Aberta
#6,599 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

type: documentation
Linguagem predominante
JavaScript
Estrelas
11.8k
Forks
7.9k
Merge médio
1d 11h
PRs com merge (30d)
11

Descrição

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.

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece pela seção “Optimizing re-renders when passing objects and functions” da página de referência de useContext e revise a explicação ao redor sobre as dependências de useMemo. Verifique o esclarecimento proposto em relação ao comportamento das referências de objetos em JavaScript e, em seguida, atualize a documentação para que o comportamento de memoização do exemplo e as atualizações imutáveis sejam inequívocos.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
javascript, react
Domínio
documentation
Tipo de issue
Documentação
Dificuldade
2/5
Tempo estimado
1-3 horas
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
45/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.