I would have thought that useEffect's first function gets called before the first render, but when I call the method below, my console.log just before the return method call gets called, then the useEffect's first parameter function gets called.
order of calls:
just before render return
ImageToggleOnScroll.js:8 useEffect before setInView
ImageToggleOnScroll.js:10 useEffect after setInView
Source:
import React, {useState,useRef,useEffect} from "react";
// primaryImg is black and white, secondaryImg is color
const ImageToggleOnMouseOver = ({ primaryImg, secondaryImg }) => {
const imageRef = useRef(null);
useEffect(() => {
console.log('useEffect before setInView')
setInView(isInView());
console.log('useEffect after setInView')
window.addEventListener("scroll", scrollHandler);
return () => {
window.removeEventListener("scroll", scrollHandler);
};
}, []);
const isInView = () => {
if (imageRef.current) {
const rect = imageRef.current.getBoundingClientRect();
return rect.top >= 0 && rect.bottom <= window.innerHeight;
}
return false;
};
const [inView, setInView] = useState(false);
const scrollHandler = () => {
setInView(() => {
return isInView();
});
};
console.log('just before render return')
return (
<img
ref={imageRef}
src={inView ? secondaryImg : primaryImg}
alt="image here"
/>
);
};
export default ImageToggleOnMouseOver;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…