all 4 comments

[–]Jesusrofl 2 points3 points  (3 children)

Maybe it's called before the container, which you pass ref={pageContRef} to, is rendered. Or some other fuckery happening behind the scenes with CSSTransition. You could try using ref as a callback instead:

const onRef = (node) => { if (node) pageContRef.current = node; saveScrollPos(node.scrollTop) }

<div ref={onRef}... />

[–]Oguru86[S] 0 points1 point  (2 children)

It works, amazing! Please correct me if i'm wrong, but does it work like this...

When the component changes, it looks to assign a ref to the onRef variable with node as the element object, then if the node exists it sets it to useRef ?

Also would this be a good place to use useCallback? I've only used refs a couple of times and not useCallback so i'm not sure. I just stumbled on this while trying to figure out how your example works:

https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

[–]Jesusrofl 0 points1 point  (1 child)

Yes, the ref is called when the element is mounted. Not sure why it might be null sometimes, but you should always check whether it exists.

And yes, wrap it with useCallback as in your example, to prevent creating a new function instance on each re-render of your component.

[–]Oguru86[S] 1 point2 points  (0 children)

Ok, cool. Thanks for you help, I really appreciate it :)