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

171
Views
Is it okay to recreate class component state behavior using useReducer?

so in react hooks we may have multiple states in our component:

const [stateA, setStateA] = useState(0);
const [stateB, setStateB] = useState('Hello World');
const [stateC, setStateC] = useState(true);

but there is a case that we need to update multiple states at once. let say when clicking event:

const handleClick = () => {
  setStateA(prev => prev+1);
  setStateB('John Doe');
  setStateC(false);
}

As we can see I need to update these states 1 by 1. So to update all states at once and ensure all updates in the same batch, I tried making this reducer:

const stateReducer => (prev, next) {
  switch (typeof next) {
    case 'object':
      return { ...prev, ...next };
    case 'function':
      return { ...prev, ...next(prev) };
    default:
      return prev;
  }

...

const [state, setState] = useReducer(stateReducer, {
  stateA: 0,
  stateB: 'Hello World',
  stateC: true
});

...

// just set single state
setState({stateA: 0});

// set multiple state
setState({
  stateA: 5,
  stateB: 'John Doe'
});

// set multiple state with prev state
setState(prev => ({
  stateA: prev.stateA +1,
  stateB: 'John Doe',
  stateC: !prev.stateC,
}));

It's works! but how it gonna affect the performace? or this is okay?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your performance will not be affected.

In the note section of the page Functional updates in the react hooks reference they post useReducer as an alternative for useState when we need to manage different state variables.

Another option is useReducer, which is more suited for managing state objects that contain multiple sub-values.

The performance key does not reside in the usage of useState or useReducer itself, it's more about why do you need to use it, and as they say in the useReducer documentation you are doing a good usage of it simplifying the way you handle this 3 state variables.

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

Not 100% sure about this but I think useState use useReducer internally.

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!