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

78
Views
Child component value not updating after set state

I am attempting to update properties on a parent object via button clicks in the child components. After clicking the increment button neither of the child components get updated.

NOTE: id is purely to differentiate between propA and B for saving state

Also is there a nice way to deal updating object properties without having to do a switch statement

Minimum reproduction

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

export default function App() {
  let [object, setObject] = useState({
    propertyA: 0,
    propertyB: 0
  });

  function handleClick(id) {
    switch (id) {
      case 1:
        setObject((prevState) => ({
          ...prevState,
          propertyA: prevState.propertyA + 1
        }));
        break;
      case 2:
        setObject((prevState) => ({
          ...prevState,
          propertyB: prevState.propertyB + 1
        }));
        break;
      default:
        console.log(id);
        break;
    }
  }

  return (
    <div className="App">
      <Child
        id="1"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />
      <Child
        id="2"
        title="property B"
        value={object.propertyB}
        handleClick={handleClick}
      />
    </div>
  );
}

function Child(props) {
  return (
    <div>
      {props.title} : {props.value}
      <button onClick={props.handleClick(props.id)}>Increment</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

onClick={props.handleClick(props.id)} should be onClick={()=>props.handleClick(props.id)}, and for the avoiding switch you can set the id as the property name

 <Child
        id="propertyA"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />

and then

function handleClick(id) {
  setObject((prevState) => ({
          ...prevState,
         [id]: prevState[id] + 1
        }))
}
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!