i am having the below state
const [data,setData] = useState({maths:null,physics:null,chem:null,percentage:null})
and i was updating the state as
setData({...data,[e.target.name]:e.target.value})
and my fuction for calculating the percentage is
function percentage(data.maths,data.physics,data.chem){
const per = ((data.maths+data.physics+data.chem)/100)*100
return per
}
my doubt is when to call this function(like useEffect or like normal) and store it in data.percentage
please help me
Try doing the function in useState as shown below and as mentioned pass the state as the array deps, so whenever any of the property in the state changes it will recalculate, which is your required output.
or as Germa suggested you can skip the function itself and do it something like this
I have added the codesandbox based on the discussion, having it in diff state will be much more better way, or else when you pass the array deps it will keep on changing.
First of all, percentage should be divided by 300 I guess.
The percentage was a part of the same data as your input field so it was causing infinite loop whenever we were setting percentage in
useEffect
. So, it’s better to separate the percentage from the input data of subjects.Working Demo
Like so:
the useEffect will run every time data changes, and data.percentage will be recalculated.