Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda