Reputation: 801
My code is meant to activate a process when it scrolls passed a point.
Everything works, but the use effect hook does not activate unless I have state change to cause a re-render. How can I change this so inactivates? When I just had a conditional internal change of the state it was both lag prone and caused a problem with changing to another page.
import React, {useEffect, useRef} from 'react';
import "./styles.css";
export default function App() {
let myRef = useRef(null);
useEffect( () => {
if (window.pageYOffset > myRef.current.offsetTop)
{ console.log("hello friend")
}
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button
onClick={() => {
console.log(myRef.current.offsetTop);
}}
>
{" "}
test
</button>
<br />
<br />
<br />
<br />
<div ref={myRef}>
<h1> hi, this is a test</h1>
<br />
<br />
<br />
<br />
</div>
</div>
);
}
here is a code pen with my exact problem. https://codesandbox.io/s/prod-silence-8f07c?file=/src/App.js
Upvotes: 1
Views: 2555
Reputation: 7642
why don't you set YoffSet
in state like so:
const [yOffSet, setYoffSet] = useState('')
then in useEffect
add a event listener:
useEffect(() => {
window.addEventListener("scroll",() => {
if(window.pageYoffSet > chooseAValue) {
setYoffSet(//whateverValueYouWant)
}
}, []);
then you are setting state and this will trigger a re-render
Upvotes: 2