// notice how none of the deps of useEffect // manages to trigger the hook in time const catImageRef = useRef() useEffect(() => { console.log(catImageRef.current) setCatInfo(catImageRef.current?.getBoundingClientRect()) // notice the warning below }, [catImageRef, catImageRef.current])
return ( <divclassName='App'> <h1>useEffect & useRef vs useCallback</h1> <p> An image of a cat would appear on every 3rd render. <br /> <br /> Would our hook be able to make the emoji see it? <br /> <br /> {catInfo ? '😂' : '😩'} - I {catInfo ? '' : "don't"} see the cat 🐈 {catInfo ? `, it's height is ${catInfo.height}` : ''}! </p> <inputdisabledvalue={`render #${count}`} /> <buttononClick={() => setCount((c) => c + 1)}>next render</button> <br /> {shouldShowImageOfCat ? ( <imgref={catImageRef}src={catImageUrl}alt='cat'width='50%'style={{padding:10 }} /> ) : ( '' )} </div> ) }
// notice how this is a useCallback // that's used as the "ref" of the image below const catImageRef = useCallback((catImageNode) => { console.log(catImageNode) setCatInfo(catImageNode?.getBoundingClientRect()) }, [])
return ( <divclassName='App'> <h1>useEffect & useRef vs useCallback</h1> <p> An image of a cat would appear on every 3rd render. <br /> <br /> Would our hook be able to make the emoji see it? <br /> <br /> {catInfo ? '😂' : '😩'} - I {catInfo ? '' : "don't"} see the cat 🐈 {catInfo ? `, it's height is ${catInfo.height}` : ''}! </p> <inputdisabledvalue={`render #${count}`} /> <buttononClick={() => setCount((c) => c + 1)}>next render</button> <br /> {shouldShowImageOfCat ? ( <imgref={catImageRef}src={catImageUrl}alt='cat'width='50%'style={{padding:10 }} /> ) : ( '' )} </div> ) }