reactjs / reactjs/react.dev

Idea-[context] StateRef provider instead of state and dispatch in separate hooks

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

Ninguém assumiu esta issue ainda.

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

Descrição

As per docs
const [state, dispatch] = useReducer(reducer,initData);
return (
    <StateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>)

as we separated state and dispatch now we can be sure that the component using only useDispatch doesn't rerender with state update.

additional boilerplate

additional boilerplate in case when a component use both state and dispatch

const state=useState()
const dispatch=useDispatch()

what if a component have to rely on the state only while handling events

const handleClick=()=>{
if(state.open){
...
}
else{
....
}
}

suggesting StateRef provider

const [state, dispatch] = useReducer(reducer,initData);
 const stateRef = React.useRef(state);
  stateRef.current=state // while rendering or preferably in effect

return (
    <StateContext.Provider value={state}>
      <StateRefContext.Provider value={stateRef}>
        <DispatchContext.Provider value={dispatch}>
        {children}
        </DispatchContext.Provider>
      </StateRefContext.Provider>
    </StateContext.Provider>)

export function useState() {
  const state= useContext(StateContext);
 const dispatch= useContext(DispatchContext);
return {state,dispatch}
}

export function useStateRef() {
  const stateRef= useContext(StateRefContext);
 const dispatch= useContext(DispatchContext);
const {stateRef,dispatch}
}

or with memoization

const [state, dispatch] = useReducer(reducer,initData);
const value={state,dispatch}
 const stateRef = React.useRef(state);
  stateRef.current=state // while rendering or preferably in effect
const refValue=useMemo(()=>({stateRef,dispatch}),[])

return (
    <StateContext.Provider value={value}>
      <StateRefContext.Provider value={refValue}>
        /*<DispatchContext.Provider value={dispatch}*/
        {children}
      </StateRefContext.Provider>
    </StateContext.Provider>)

we can use either one of the hooks based on how a component depended on the state
const {state,dispatch}=useState() //for rendering
//                 or
const {stateRef,dispatch}=useStateRef() //for referring state

// based on how a component depended on the state

useStateProvider can be used when a component uses the state and Having dispatch provided with it doesn't do any harm.

useStateRefProvider can be used when a component has to refer to the state in only event handlers. Instead of wrapping a component or prop drilling an event handler corresponding to where a component has been used.
Thus increasing the reusability of the components

If it is wrong or an absolute anti-pattern please correct me, it will help in deepening my understanding

It is my first time writing in github, It`s unintentional if I failed to comply with your contributing guidelines

thank you

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

Nenhum arquivo ou teste é nomeado. Comece revisando os padrões documentados de useReducer, useContext, useState e useDispatch e, em seguida, determine se um provider StateRef e o hook useStateRef se encaixam no projeto; para considerar o trabalho concluído, seria necessário ter um design acordado, um uso documentado e quaisquer exemplos ou testes correspondentes.

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
Funcionalidade
Dificuldade
5/5
Tempo estimado
Mais de uma semana
Status de atividade
Estagnada
Clareza
Precisa de esclarecimento
Facilidade para iniciantes
20/100

Receba novas issues na sua caixa de entrada

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