Last active
July 1, 2021 01:26
-
-
Save stivsk/4aa05963f4a981470b15d51b729e6e90 to your computer and use it in GitHub Desktop.
Simple Parallax React Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/TheClosure/parallax-tutorial | |
import { useEffect, useState } from 'react'; | |
const useParallax = (speed = 0.5) => { | |
const [offsetY, setOffsetY] = useState(0); | |
const handleScroll = () => setOffsetY(window.pageYOffset); | |
useEffect(() => { | |
window.addEventListener('scroll', handleScroll); | |
return () => window.removeEventListener('scroll', handleScroll); | |
}, []); | |
return { | |
transform: `translateY(${offsetY * speed}px)`, | |
}; | |
}; | |
export default useParallax; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const parallaxStyle = useParallax();
<div className="someBackground" style={parallaxStyle} />