Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
is it alright to have a ref on state (from a reducer) to avoid creating new callbacks?

I often have a use case where there is some state in reducer and it needs to be accessed in some callback (useCallback) as well

const [state, dispatch] = useReducer(reducer, initialState);
...
const handleAction = useCallback(()=>{
   // dependency on state 
},[])

to avoid running useCallbacks on every state change, I reach out for a ref and have the state assigned to it on every render

 stateRef.current = state;

and then where ever i have to use something from state in a callback, it is accessed from the stateRef. Is this a right way of doing it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you are simply updating the stateRef from the component body then this isn't the most correct way as this would be considered an unintentional side-effect. If not using an useCallback hook with a dependency on the state to re-enclose the current state value in a callback function then an useEffect with a dependency on the state value is suggested.

const [state, dispatch] = useReducer(reducer, initialState);
const stateRef = useRef();

useEffect(() => {
  stateRef.current = state;
}, [state]);

const handleAction = ()=>{
  // access stateRef.current
};

This is effectively what useCallback accomplishes though, but in a more succinct way.

const [state, dispatch] = useReducer(reducer, initialState);

const handleAction useCallback(() => {
  // access current state value closed over in scope
}, [state]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda