Skip to content

Instantly share code, notes, and snippets.

@stivsk
Last active July 1, 2021 01:26
Show Gist options
  • Save stivsk/4aa05963f4a981470b15d51b729e6e90 to your computer and use it in GitHub Desktop.
Save stivsk/4aa05963f4a981470b15d51b729e6e90 to your computer and use it in GitHub Desktop.
Simple Parallax React Hook
// 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;
@stivsk
Copy link
Author

stivsk commented Jul 1, 2021

const parallaxStyle = useParallax();
<div className="someBackground" style={parallaxStyle} />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment