-1

i want to get 15 value here.. but when i useEffect it give 30; I want to do like this. i know there are another way but what if when i have dynamic value. so, i want to know, how can i solve this code.

function ChildComponent({setSum}) {
  const value = 5;

useEffect(()=>{
  setSum((prev)=> prev + value)
},[setSum, value])

  return (
    <div>
      <p>Random value: {value}</p>
    </div>
  );
}

export default function App() {
  const [sum, setSum] = useState(0);

// i want to get 15 value here.. but when i useEffect it give 30;

  return (
    <div>
        {[1,2,3].map((_, i) => (
          <ChildComponent key={i} setSum={setSum}/>
        ))}
      <p>Sum: {sum}</p>
    </div>
  );
}



export default function App() {
  const [sum, setSum] = useState(0);

// i want to get 15 value here.. but when i useEffect it give 30;

  return (
    <div>
        {[1,2,3].map((_, i) => (
          <ChildComponent key={i} setSum={setSum}/>
        ))}
      <p>Sum: {sum}</p>
    </div>
  );
}
  • I'm pretty sure `useEffect()` is not the hook you need here. Could you please describe declaratively what you want this app to do? If we know what you want to achieve, we can help you better. – Designly Feb 22 '23 at 11:51
  • assume, the 3 child component generates value randomly. so, I want to get those values and the sum of values. – Nazmul Islam Nahid Feb 22 '23 at 12:05
  • I will init an array state in parent's component. Array.from(new Array(3), ()=>Math.random()) and send this state to child as a prop. – YinPeng.Wei Feb 22 '23 at 12:16

1 Answers1

1

useEffect will be called twice in StriceMode in React 18. See more: Why useEffect running twice and how to handle it well in React?

https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state

I try to implement your feature here. If helps ,please vote for me. https://codesandbox.io/s/trusting-flower-mykxot?file=/src/App.tsx

  1. you can try to use Math.floor(Math.random() * 10 ) in useState instead of 5 and see the result.
  2. you can try to delete disabled prop of input, and edit number in the it.
YinPeng.Wei
  • 552
  • 3
  • 9