1

I have some inputs defined in react. I'm assigning a function to their onChange function. I can find the current value. How can I get the old value in simplest way?

The reason I want this is because I want to find the ratio of this new value to the old value and do some operations.

Sample code:

let onChange = (e) => {
    let newValue = e.target.value; // let oldValue = will be here     

}

<Input type="number"  onChange={onChange }></Input>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hamdi
  • 67
  • 2
  • 10
  • You probably need `useRef` to store the old value and compare it with the current. https://reactjs.org/docs/hooks-reference.html#useref – Delice Aug 23 '21 at 12:47
  • I create the inputs dynamically and add the event to them at that time. It is unclear how many references there will be for this. – hamdi Aug 23 '21 at 13:20
  • let [layerArr, setLayerArr] = React.useState([]) – hamdi Aug 23 '21 at 13:21
  • ``` {layerArr.map((layer, index) => { return (
    ) })} ```
    – hamdi Aug 23 '21 at 13:22
  • I mean the number of inputs changes dynamically. and accordingly the UI is updated again – hamdi Aug 23 '21 at 13:24

2 Answers2

4

You can use a state to do it:

const [state, setState] = useState("");

let onChange = (e) => {
  let oldValue = state; 
  let newValue = e.target.value;
  setState(newValue)
  // your logic
};

<Input type="number" value={state} onChange={onChange}></Input>;
Viet
  • 12,133
  • 2
  • 15
  • 21
3

If the old value is not needed in the component state, use a ref like the following, you can change its initial value

const oldValueRef = React.useRef(0)

let onChange = (e) => {
    const oldValue = oldValueRef.current;
    let newValue = e.target.value; // let oldValue = will be here

    // after everything     
    oldValueRef.current = e.target.value;
}

<Input type="number" onChange={onChange }></Input>
iunfixit
  • 953
  • 3
  • 15
  • i was able to do it by applying the solution [here](https://stackoverflow.com/questions/54633690/how-can-i-use-multiple-refs-for-an-array-of-elements-with-hooks) thanks – hamdi Aug 24 '21 at 05:06