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

131
Visualizações
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 Respostas
Responde à pergunta

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 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