Top React Hooks — Scroll and Breakpoints

Image for post
Image for post
Photo by Kalen Emsley on Unsplash

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

The react-use library is a big library with many handy hooks.

The useScrolling hook lets us keep track of whether the user is scrolling an element or not.

To use it, we can write:

We create the ref that we pass into the element that we want to watch the scrolling for.

Also, we pass the ref to the element to the useScrolling hook.

The hook returns the scrolling state of the element.

The useScrollbarWidth hook returns the browser’s scrollbar width.

It’ll return undefiuned until the DOM is ready.

For instance, we can write:

We have the useScrollbarWidth hook which returns the scroll bar width.

The useWindowSize hook returns the dimensions of the browser window.

For instance, we can write:

We called the useWindowSize hook to get the width and height of the window.

We can use the useMeasure hook to get the dimensions of an HTML element.

It uses the resize observer API to do so.

For example, we can write:

x and y are the x and y coordinates of the top left corner of the element.

width and height are their width and height.

top , right , bottom , and left are the position values of the element.

The createBreakpoint function creates the useBreakpoint hook lets us detect screen width breakpoints.

For instance, we can write:

We have the useBreakpoint hook which returns the breakpoint that matches the screen size.

Also, we can change the breakpoints by passing in an object to createBreakpoint :

We pass in an object with the breakpoint names as the keys and the widths as the values.

Then we use useBreakpoint the same way.

Conclusion

The react-use package has hooks to detect widths and detect scrolling.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store