55

I'm still getting my head around react hooks but struggling to see what I'm doing wrong here. I have a component for resizing panels, onmousedown of an edge I update a value on state then have an event handler for mousemove which uses this value however it doesn't seem to be updating after the value has changed.

Here is my code:

export default memo(() => {
  const [activePoint, setActivePoint] = useState(null); // initial is null

  const handleResize = () => {
    console.log(activePoint); // is null but should be 'top|bottom|left|right'
  };

  const resizerMouseDown = (e, point) => {
    setActivePoint(point); // setting state as 'top|bottom|left|right'
    window.addEventListener('mousemove', handleResize);
    window.addEventListener('mouseup', cleanup); // removed for clarity
  };

  return (
    <div className="interfaceResizeHandler">
      {resizePoints.map(point => (
        <div
          key={ point }
          className={ `interfaceResizeHandler__resizer interfaceResizeHandler__resizer--${ point }` }
          onMouseDown={ e => resizerMouseDown(e, point) }
        />
      ))}
    </div>
  );
});

The problem is with the handleResize function, this should be using the latest version of activePoint which would be a string top|left|bottom|right but instead is null.

Andry
  • 15,262
  • 25
  • 130
  • 229
Simon Staton
  • 4,165
  • 4
  • 24
  • 48
  • Whats the value of point if you do `console.log(point)`, just above `setActivePoint(point)`. I am wondering if `resizerMouseDown` it's even called. – Nicholas Mar 20 '19 at 16:11
  • It would seem that your `.addEventListener(` calls are using the current functions in that render, therefore, when you change `activePoint` and rerender those event listeners are not updated to point to the new `activePoint` – Andria Mar 20 '19 at 16:19

7 Answers7

77

useRef to read future value

Currently, your issue is that you're reading a value from the past. When you define handleResize it belongs to that render, therefore, when you rerender, nothing happens to the event listener so it still reads the old value from its render.

To fix this, you should use a ref via useRef that you keep updated so that you can read the current value.

Example (link to jsfiddle):

  const [activePoint, _setActivePoint] = React.useState(null);

  // define a ref
  const activePointRef = React.useRef(activePoint);

  // in place of original `setActivePoint`
  const setActivePoint = x => {
    activePointRef.current = x; // keep updated
    _setActivePoint(x);
  };

  const handleResize = () => {
    // now when reading `activePointRef.current` you'll
    // have access to the current state
    console.log(activePointRef.current);
  };

  const resizerMouseDown = /* still the same */;

  return /* return is still the same */
Andria
  • 3,832
  • 2
  • 19
  • 37
  • 1
    this solution is too noisy. I like to use the setActivePoint method instead (see other answers) – Derek Liang Mar 05 '20 at 07:09
  • @derekliang the OP doesn't want to `setActivePoint` on `handleResize` tho. That would cause way too many updates to the screen. This way, `setActivePoint` is only called once on `resizerMouseDown` but the logging in `handleResize` is independent of re-renders. – Andria Mar 05 '20 at 12:41
  • If the state don't change, it will not update the screen. It will cause the state change check but fail to see the change, therefore there is no update to the screen. – Derek Liang Mar 05 '20 at 22:09
  • 1
    I misspoke, I meant that it would force an update in React. While React knows not to rerender to the DOM, it is still costly to perform hundreds/thousands of checks to see if nothing has changed yet since `handleResize` is attached to the `mousemove` event. – Andria Mar 05 '20 at 22:34
  • What not make use of the useCallback hook? This should prevent stale event handlers? – Joseph King May 09 '20 at 14:32
  • You're right, however, to prevent stale event handlers you have to constantly create new event handlers and mousemove causes an insane amount of updates so it's not feasible to use `useCallback` and stay performant. – Andria May 10 '20 at 01:13
  • @ChrisBrownie55 The documentation for useState states "If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely.". In practice, when calling setState without changing the state, the outcome is that the component renders partially once (without re-rendering children) to verify that nothing in the component output changed. If nothing changed, subsequent setState calls without modifying the state cause no additional internal renders. – voneiden Oct 15 '20 at 09:04
  • @voneiden What's your concern about? – Andria Oct 16 '20 at 02:37
  • @ChrisBrownie55 concerning the earlier statement that "it would force an update in React" and that "it is still costly to perform hundreds/thousands checks". So my concern is mainly that while the performance penalty is definitely greater with setState, I'm not convinced it is significantly so under normal operating conditions (meaning if the setState bails out from updating rerendering correctly). Of course, that's just a guess on my behalf, since I haven't run any actual perf tests comparing the two methods. – voneiden Oct 16 '20 at 12:09
  • @voneiden I think at this point it might as well just be preference. I personally believe it's easier to reason about when you know that a ref is being used. No need to use your `setState` as a way to get React to give you the **current** state when you can just `useRef` IMO – Andria Oct 16 '20 at 14:36
  • @ChrisBrownie55 Sure, fully agreed. My intent wasn't to dispute the answer, but simply to question the comment related to the perf impact of using setState. Sorry for being unclear on the matter. – voneiden Oct 17 '20 at 18:02
  • 1
    I have the same problem as the OP, but multiplied. I have several event handlers that use several different pieces of state, which call several other internal functions. This is on a component that was formerly class-based that I'm switching over to functional because I want `useEffect`. Anyway, the whole situation feels very buggy to me. It's surprising that a piece of state might be able to get an old value at all. Is the `useRef` + `statePiece.current` fix still the best solution? – Mike Willis Mar 02 '21 at 15:08
32

You have access to current state from setter function, so you could make it:

const handleResize = () => {
  setActivePoint(activePoint => {
    console.log(activePoint);
    return activePoint;
  })
};
machnicki
  • 403
  • 5
  • 3
  • 3
    Is there a reason why this isn't a preferred solution over the recognized answer? Very concise. Also why does this work? How does it fix the scoping issue? – aturc Sep 12 '20 at 00:46
  • 3
    @aturc setState supports functional updates: if a function is passed to setState it receives the current state as the first argument. The function must return a new state. If the new state is the same as the old state, render is skipped. So it can be utilized to do side effects. https://reactjs.org/docs/hooks-reference.html#functional-updates – voneiden Oct 15 '20 at 07:59
  • 1
    Not sure if this is good solution. setState is not supposed to run arbitrary code. – Nitin Jadhav Feb 25 '21 at 14:16
  • After having used the `ref` method (defining your own state-setter function that also updates a ref), I'm starting to prefer this method instead, specifically in functional components with `useEffect` (or similar hooks that have a dependency array). Mainly because if you use the `ref` method with any `useEffects`, you end up having to pass your setter function into the `useEffect`, which I find irritating. – Mike Willis Aug 23 '21 at 13:51
6
  const [activePoint, setActivePoint] = useState(null); // initial is null

  const handleResize = () => {
    setActivePoint(currentActivePoint => { // call set method to get the value
       console.log(currentActivePoint);  
       return currentActivePoint;       // set the same value, so nothing will change
                                        // or a different value, depends on your use case
    });
  };

Derek Liang
  • 1,023
  • 1
  • 15
  • 22
4

For those using typescript, you can use this function:

export const useReferredState = <T>(
    initialValue: T = undefined
): [T, React.MutableRefObject<T>, React.Dispatch<T>] => {
    const [state, setState] = useState<T>(initialValue);
    const reference = useRef<T>(state);

    const setReferredState = (value) => {
        reference.current = value;
        setState(value);
    };

    return [state, reference, setReferredState];
};

And call it like that:

  const [
            recordingState,
            recordingStateRef,
            setRecordingState,
        ] = useReferredState<{ test: true }>();

and when you call setRecordingState it will automatically update the ref and the state.

johannb75
  • 317
  • 3
  • 14
3

Just small addition to the awe ChrisBrownie55's advice.

A custom hook can be implemented to avoid duplicating this code and use this solution almost the same way as the standard useState:

// useReferredState.js
import React from "react";

export default function useReferredState(initialValue) {
    const [state, setState] = React.useState(initialValue);
    const reference = React.useRef(state);

    const setReferredState = value => {
        reference.current = value;
        setState(value);
    };

    return [reference, setReferredState];
}


// SomeComponent.js
import React from "react";

const SomeComponent = () => {
    const [someValueRef, setSomeValue] = useReferredState();
    // console.log(someValueRef.current);
};
Nikita
  • 89
  • 1
  • 3
3

useRef for the callback

Beside the correct way suggested by ChrisBrownie55, you can have a similar approach, which might be easier to maintain, by using useRef for the eventListener's callback itself, instead of the useState's value.

In this way you shouldn't be worried about saving in a reference every useState you would like to use in the future.

Just save the handleResize in a ref and update its value on every render:

const handleResizeRef = useRef(handleResize)
handleResizeRef.current = handleResize;

and use the handleResizeRef as a callback, wrapped in an arrow function:

window.addEventListener('mousemove', e => handleResizeRef.current(e));

Sandbox example

https://codesandbox.io/s/stackoverflow-55265255-answer-xe93o?file=/src/App.js

Full code using custom hook:

/* 
this custom hook creates a ref for fn, and updates it on every render. 
The new value is always the same fn, 
but the fn's context changes on every render
*/
const useRefEventListener = fn => {
  const fnRef = useRef(fn);
  fnRef.current = fn;
  return fnRef;
};

export default memo(() => {
  const [activePoint, setActivePoint] = useState(null);

  const handleResize = () => {
    console.log(activePoint);
  };

  // use the custom hook declared above
  const handleResizeRef = useRefEventListener(handleResize)

  const resizerMouseDown = (e, point) => {
    setActivePoint(point);
    // use the handleResizeRef, wrapped by an arrow function, as a callback
    window.addEventListener('mousemove', e => handleResizeRef.current(e));
    window.addEventListener('mouseup', cleanup); // removed for clarity
  };

  return (
    <div className="interfaceResizeHandler">
      {resizePoints.map(point => (
        <div
          key={ point }
          className={ `interfaceResizeHandler__resizer interfaceResizeHandler__resizer--${ point }` }
          onMouseDown={ e => resizerMouseDown(e, point) }
        />
      ))}
    </div>
  );
});
  • 1
    Are you sure this works? I tried it with my own code and I was still having the old (initial?) value – user2078023 Feb 10 '21 at 14:31
  • @user2078023 there was a typo sorry, "handleResizeRef" was "hanleResizeRef". Please check the code working in this sandbox https://codesandbox.io/s/stackoverflow-55265255-answer-xe93o?file=/src/App.js – Davide Cantelli Feb 11 '21 at 16:03
0

You can make use of the useEffect hook and initialise the event listeners every time activePoint changes. This way you can minimise the use of unnecessary refs in your code.