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

100
Views
React Component does not re rendering when updating an object in state hooks

Why this component does not update when the state updating? But, when the file is updated (like editing and saving the code), the component will re-rendering and show the correct value from the updated state. Here is the code

import { useReducer } from "react";
import "./styles.css";

const init = [
  {
    name: "Car",
    stock: 100
  },
  {
    name: "Truck",
    stock: 50
  }
];

const reducer = (state, action) => {
  if (action.type === "add") { 
    state[0].stock++;
    return state;
  } else { 
    return state;
  }
};


export default function App() {
  const [state, dispatch] = useReducer(reducer, init);
  const addCarStock = () => {
    dispatch({ type: "add" });
  };

  return (
    <div>
      <p>Car Stock : {state[0].stock}</p>
      <button onClick={addCarStock}>Add Car Stock</button>
    </div>
  );
}

You can open this code in sandbox.io

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

0

When you do state[0].stock++;. It changes the existing array(you can actually check that array updated by putting a console.log(state); in the first line of reducer function) and when react does rendering it does a shallow comparison (reference checking) and ignores re-render assuming it is the same array (because prev and new state refer to the same instance).

You need to create a new array instance (state) with the changes and return it.

const reducer = (state, action) => {
  if (action.type === "add") {
    return state.map((item,itemIndex) => {
      if(itemIndex === 0){
        return {...item, stock: item.stock + 1}
      } else {
        return item;
      }
    });
  } else {
    return state;
  }
};

Code sandbox => https://codesandbox.io/s/recursing-davinci-iid5h?file=/src/App.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!