Member-only story
Top React Hooks — Scroll, Battery, and Pub/Sub
3 min readOct 9, 2020
Hooks contains our logic code in our React app.
We can create our own hooks and use hooks provided by other people.
In this article, we’ll look at some useful React hooks.
react-use-scroll-position
The react-use-scroll-position package lets us watch the scroll position within our React component.
To install it, we run:
npm i react-use-scroll-position
Then we can use it by writing:
import React from "react";
import {
useScrollPosition,
useScrollXPosition,
useScrollYPosition
} from "react-use-scroll-position";export default function App() {
const { x, y } = useScrollPosition();
const scrollX = useScrollXPosition();
const scrollY = useScrollYPosition();
return (
<>
<p style={{ position: "fixed" }}>
{x}, {y}, {scrollX}, {scrollY}
</p>
{Array(1000)
.fill()
.map((_, i) => (
<p>{i}</p>
))}
</>
);
}
We called the useScrollPosition
, the useScrollXPosition
, and useScrollYPosition
hooks to get the x and y coordinates of the scroll position.
x
should be the same as scrollX
.