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

134
Vistas
How can I make this redux function more efficient?

My initial version did not use cloning. However useSelector() was not firing until I added another clone statement.

I thought that by cloning the containing object on a state change this would cause it tor fire. Particularly this line here.

  let newState = { ...state };

That is a sub question. Why does not returning a new state cause useSelector to fire.

I had to add a second clone to get it to fire as follows:

const clone = [...newState.messages];

I find this behavior odd, and wonder if it might be a bug. Also not very efficient to have to clone my messages array.

The complete reducer is as follows:

const Messages = (state = {messages: false}, action) => {
  let newState = { ...state };
  switch(action.type) {
  case 'initializeMessages':
    newState.messages = action.messages;
    return newState;
  case 'addMessage':
    // cloning is required to make useSelector() fire
    const clone = [...newState.messages];
    clone.unshift(action.message);
    newState.messages = clone;
    return newState;
  }
  return state;
};

and I use it as follows:

Updating

  const messages = useSelector( (state) => state.Messages.messages );

Dispatching

dispatch({type: 'addMessage', message: message});

UPDATE

After updating to hooks, my reduces don't work anymore unless I clone embedded arrays. Before I did not have to do this:

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you are right, you need to do the same for addMessage block like:

const newState = {
    ...state,
    messages: [
        ...newState.messages,
        action.message
    ]
};
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