const [checkBoxValue, setCheckBoxValue] = useState(false)
// useEffect - a.k.a component first mounts
useEffect(() => {
console.log('in useEffect')
return () => {
console.log('cleanup')
};
// [] - An array that contains a list of dependencies for the component. If an array is empty then useEffect is only called once when the component is first mounted.
// if you decide to call this again , you will need values in thi array that change, a.k.a the values that the rendered output is dependent on.
}, [checkBoxValue]) // if 'checkBoxValue' changes, then that causes a re-render of the component, and a function that uses useEffect is called again.
More React Hooks
3 Commonly used React Hooks
import React, {useRef, useEffect, useState} from "react"
const ImageTogglerOnScroll = ({ primaryImg, secondaryImg }) => {
const imageRef = useRef(null)
const [isLoading,setIsLoading] = useState(true)
const [inView,setInView] = useState(false)
useEffect(() => {
window.addEventListener("scroll", scrollHandler)
setInView(isInView())
setIsLoading(false)
return ( () => {
window.removeEventListener("scroll", scrollHandler)
})
},[isLoading])
const isInView = () => {
if (imageRef.current) {
const rect = imageRef.current.getBoundingClientRect()
return rect.top >= 0 && rect.bottom <= window.innerHeight
}
return false
}
const scrollHandler = () => {
setInView(() => {
return isInView()
})
}
// if isLoading is true then do not render anything
return isLoading ? null : (
<img
src={inView ? secondaryImg : primaryImg}
alt="" ref={imageRef} width="200" height="200"
/>
)
}
export default ImageTogglerOnScroll
import React from "react";
import ImageToggleOnScroll from "../src/ImageToggleOnScroll";
const ImageChangeOnScroll = () => {
return (
<div>
{[1124, 187, 823, 1269, 1530].map(speakerId => {
return (
<div key={speakerId}>
<ImageToggleOnScroll
primaryImg={`/static/speakers/bw/Speaker-${speakerId}.jpg`}
secondaryImg={`/static/speakers/Speaker-${speakerId}.jpg`}
alt=""
/>
</div>
);
})}
</div>
);
};
export default ImageChangeOnScroll;