I have big list of photo thumbnails, and I should be able to scroll one of thumbnails into view when list is loaded.
Photos are populated with map
function, and one of the thumbnails' container div will be given ref
.
I tried useEffect:
useEffect(() => {
if (scrollRef.current && scrollRef.current instanceof HTMLDivElement) {
scrollRef.current.scrollIntoView({
behavior: 'auto',
block: 'center',
inline: 'center',
});
}
}, [scrollRef.current]);
Problem is that ref
or ref.current
cannot be used as dependency list of useEffect. I get warning:
React Hook useEffect has an unnecessary dependency: 'scrollRef.current'. Either exclude it or remove the dependency array. Mutable values like 'scrollRef.current' aren't valid dependencies because mutating them doesn't re-render the component
How can I fire useEffect or some other function when ref.current
changes? And by changes, I mean specifically its clientHeight value changes. Because initially it is zero, and scrollIntoView
does not work yet.
Use a callback ref.