event listener does not get latest state values react native

Solutions on MaxInterview for event listener does not get latest state values react native by the best coders in the world

showing results for - "event listener does not get latest state values react native"
Augustina
27 Oct 2020
1// useRef to read future value
2// Currently, your issue is that you're reading a value from the past. 
3// When you define handleResize it belongs to that render, therefore, 
4// when you rerender, nothing happens to the event listener so it still reads the old value from its render.
5
6// To fix this, you should use a ref via useRef that you keep updated so that you can read the current value.
7
8  const [activePoint, _setActivePoint] = React.useState(null);
9  // define a ref
10  const activePointRef = React.useRef(activePoint);
11  // in place of original `setActivePoint`
12  const setActivePoint = x => {
13    activePointRef.current = x; // keep updated
14    _setActivePoint(x);
15  };
16  const handleResize = () => {
17    // now when reading `activePointRef.current` you'll
18    // have access to the current state
19    console.log(activePointRef.current);
20  };
21  const resizerMouseDown = /* still the same */;
22  return /* return is still the same */