reactjs / reactjs/react.dev

[Suggestion]: remove the caveat for writing ref in render path

Aberta
#6,925 1 comentário 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

In the doc for ref https://react.dev/reference/react/useRef#caveats, it calls out to not read/write ref in rendering phase without a very clear "bad example"

Page

No response

Details

However, there is use case where the caller just needs a static ref at component level to wrap a dynamic value: for example, I need to read/write a static ref in rendering path (keep it in-sync with the current render context value)

In another word, the argument could be "a need to read/sync a "render context" value into a static variable attached to the functional component", + the "ref" value is not use in the "return" of the functional component

const { componentId, renderId } = useContext(componentContext);
const context = { componentId, renderId } <--- dynamic

const contextRef  =  useRef(context); <--- static
contextRef.current = context;

useQuery({
  context: contextRef  <--- static ref to avoid equal check, the ref value is only used for logging
})

e.g. https://github.com/apollographql/apollo-client/issues/11835

and there are popular library like useLatest implemented by writing ref in render path

Can we remove or update the caveat to make it more clear? E.g. adding

If you don't attempt to use the "mutable" ref in determining the function return, it is fine to use it to sync rendering context

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

Revise a seção de ressalvas de useRef em https://react.dev/reference/react/useRef#caveats e compare suas orientações com a issue do Apollo Client e a implementação de useLatest vinculadas no relatório. Esclareça se a ressalva deve ser removida ou revisada para refs sincronizadas durante a renderização sem afetar o retorno do componente; em seguida, atualize a documentação e verifique se a redação resultante é inequívoca.

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
3/5
Tempo estimado
1-2 dias
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

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