Top React Hooks — Lock Scrolling, Animation Loop, Session Storage, and Throttling

Image for post
Image for post
Photo by Anders Wideskott 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.

useLockBodyScroll

The useLockBodyScroll hook lets us lock the scrolling of the body element.

It’s useful for modals and overlays.

It takes an argument to let us lock scrolling or not.

For example, we can write:

We have a button to toggle the locked state.

If it’s true , we disable locking scrolling on the body.

Otherwise, we let users scroll the body.

useRafLoop

The useRafLoop hook lets us run the requestAnimationFrame loop without re-rendering the parent component.

The loop stops automatically on component unmount.

For instance, we can write:

We use the useRafLoop hook by passing in callback with the time , which is the timestamp since the loop started.

The timestamp is in milliseconds.

It returns an array with the loopStop , loopStart and isActive variables.

loopStop lets us stop the requestAnimationFrame loop.

loopStart lets us start the requestAnimationFrame loop.

isActive is true when the requestAnimationFrame loop is active.

useSessionStorage

The useSessionStorage hook lets us manage our browser’s session storage.

To use it, we write:

The useSessionStorage hook takes the key for the session storage as the first argument.

The 2nd argument is the value for the given key.

It returns the value and setValue variables to let us get and set the value respectively.

useThrottle

We can use the useThrottle hook to throttle the value updates.

To use it, we can write:

We call the useThrottle hook, which takes the state value and the number of milliseconds to delay the updates.

Then we render both the unthrottled and throttled values.

Conclusion

We can throttle state updates, lock scrolling, run the requestAnimationFrame loop, and manage session storage with the react-use library.

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