Skip to content

Commit 127a5a1

Browse files
Refactor Parallax
1 parent 9a5d943 commit 127a5a1

File tree

1 file changed

+5
-22
lines changed

1 file changed

+5
-22
lines changed

src/components/Common/Parallax.tsx

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,15 @@ import { animated, useSpring } from "@react-spring/web";
66
interface ParallaxProps {
77
children: ReactNode;
88
className?: string;
9-
maxOffset?: string; // e.g. "8rem"
9+
maxOffset?: number; // max offset in pixels
1010
speed?: number; // e.g. 0.2
11-
thresholdPx?: number; // change threshold to avoid tiny updates (default 0.5px)
1211
}
1312

1413
export default function Parallax({
1514
children,
1615
className = "",
17-
maxOffset = "8rem",
16+
maxOffset = 128,
1817
speed = 0.2,
19-
thresholdPx = 0.5,
2018
}: ParallaxProps) {
2119
const hostRef = useRef<HTMLDivElement>(null);
2220

@@ -29,21 +27,6 @@ export default function Parallax({
2927
const el = hostRef.current;
3028
if (!el) return;
3129

32-
// ---- convert CSS unit -> px (once) ----
33-
const toPx = (value: string) => {
34-
// single detached element reused for measurement
35-
const probe = document.createElement("div");
36-
probe.style.position = "absolute";
37-
probe.style.visibility = "hidden";
38-
probe.style.height = value;
39-
document.body.appendChild(probe);
40-
const px = probe.offsetHeight;
41-
probe.remove();
42-
return px;
43-
};
44-
const maxOffsetPx = toPx(maxOffset);
45-
46-
// ---- state we keep outside React render ----
4730
let rafId: number | null = null;
4831
let latestScrollY = window.scrollY;
4932
let lastApplied = -1; // last y we sent to spring
@@ -58,8 +41,8 @@ export default function Parallax({
5841
rafId = null;
5942
if (!shouldRun()) return;
6043

61-
const offset = Math.min(latestScrollY * speed, maxOffsetPx);
62-
if (Math.abs(offset - lastApplied) >= thresholdPx) {
44+
const offset = Math.min(latestScrollY * speed, maxOffset);
45+
if (Math.abs(offset - lastApplied) >= 0.5) {
6346
lastApplied = offset;
6447
// fire only if value changed enough
6548
api.start({ y: offset });
@@ -115,7 +98,7 @@ export default function Parallax({
11598
ro.disconnect();
11699
if (rafId != null) cancelAnimationFrame(rafId);
117100
};
118-
}, [api, maxOffset, speed, thresholdPx]);
101+
}, [api, maxOffset, speed]);
119102

120103
return (
121104
<div ref={hostRef} className={`relative ${className}`}>

0 commit comments

Comments
 (0)