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

133
Vistas
Which method to use when updating state inside React.useReducer

Lets imagine a simple reducer:

const [state, setState] = React.useReducer(myReducer, {})

And myReducer with one single case (simplified version):

const myReducer = (state, action) => {
  switch (action.type) {
    case 'UPDATE_STATE': {
      // Code to update here...
    }
  }
}

Now, which of the following statements is best suited to update a state - and why:

NOTE: payload = state.

METHOD 1

case 'UPDATE_STATE': {
      const updatedState = action.payload

      updatedState.object = true

      return updatedState
    }

METHOD 2

case 'UPDATE_STATE': {
      const updatedState = action.payload

      updatedState.object= true

      return { ...state, updatedState }
    }

METHOD 3

case 'UPDATE_STATE': {
      const updatedState = action.payload

      updatedState.object= true

      return { ...state, ...updatedState }
    }

METHOD 4

case 'UPDATE_STATE': {
      return ({ ...state, object: true })
    }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think you should Use method 4. You are not mutating the state here, which is the React way.

case 'UPDATE_STATE': {
      return ({ ...state, object: true })
    }

Note: Spread operator ... creates different references up to one level only.

EDIT: Based on comments, here is a simple example of how you could be mutating state, even with the simplest of objects if you are not using ....

let state = { object : true};
let payload = state;
state.object = false;
console.log(state);
console.log(payload);

Even with ... you might have deeply nested objects. They will have the same problem, unless you want to spread at every level. There are libraries to help you with deep objets like immutable.js.

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