Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!