Categories
React Hooks

Top React Hooks — Observables and Hooks

Spread the love

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 Hooks for RxJS

The React Hooks for RxJS library lets us use Rxjs observables in our React components.

To install it, we can run:

npm i --save rxjs-hooks

or:

yarn add rxjs-hooks

We can use it by writing:

import React from "react";
import { useObservable } from "rxjs-hooks";
import { interval } from "rxjs";
import { map } from "rxjs/operators";

export default function App() {
  const value = useObservable(() => interval(2000).pipe(map(val => val * 2)));

  return (
    <div className="App">
      <h1>{value}</h1>
    </div>
  );
}

We use the interval observable with the useObservable hook.

It returns the value of the observable.

The pipe operator lets us modify the value generated from the interval observable.

It also comes with the useEventCallback hook to let us watch for event object changes.

For instance, we can write:

import React from "react";
import { useEventCallback } from "rxjs-hooks";
import { map } from "rxjs/operators";

export default function App() {
  const [clickCallback, [description, x, y]] = useEventCallback(
    event$ =>
      event$.pipe(
        map(event => [event.target.innerHTML, event.clientX, event.clientY])
      ),
    ["nothing", 0, 0]
  );

  return (
    <div className="App">
      <p>
        click position: {x}, {y}
      </p>
      <p>{description} was clicked.</p>
      <button onClick={clickCallback}>click foo</button>
      <button onClick={clickCallback}>click bar</button>
      <button onClick={clickCallback}>click baz</button>
    </div>
  );
}

We called the useEventCallback hook with a callback that takes th event$ observable.

It returns the piped results returned from the pipe operator.

map lets us return an object we can get the click event object properties from.

The hook returns an array with the clickCallback that we can use as click handlers.

The 2nd entry is the click event object.

The 3rd argument is an array with the initial values of the properties in the click event object.

Scroll Data Hook

The Scroll Data Hook library lets us return information about scroll speed, distance, direction, and more.

To use it, we can install it by running:

yarn add scroll-data-hook

Then we can use it by writing:

import React from "react";
import { useScrollData } from "scroll-data-hook";

export default function App() {
  const {
    scrolling,
    time,
    speed,
    direction,
    position,
    relativeDistance,
    totalDistance
  } = useScrollData({
    onScrollStart: () => {
      console.log("Started scrolling");
    },
    onScrollEnd: () => {
      console.log("Finished scrolling");
    }
  });

  return (
    <div>
      <div style={{ position: "fixed" }}>
        <p>{scrolling ? "Scrolling" : "Not scrolling"}</p>
        <p>Scrolling time: {time} milliseconds</p>
        <p>Horizontal speed: {speed.x} pixels per second</p>
        <p>Vertical speed: {speed.y} pixels per second</p>
        <p>
          Position: {position.x} {position.y}
        </p>
        <p>
          Direction: {direction.x} {direction.y}
        </p>
        <p>
          Relative distance: {relativeDistance.x}/{relativeDistance.y}
        </p>
        <p>
          Total distance: {totalDistance.x}/{totalDistance.y}
        </p>
      </div>
      <div>
        {Array(1000)
          .fill()
          .map((_, i) => (
            <p key={i}>{i}</p>
          ))}
      </div>
    </div>
  );
}

We call the useScrollData hook with the object that has a callback that runs when we scroll.

onScrollStart runs when we start scrolling.

onScrollEnd runs when we stop scrolling.

The hook returns an object with various properties.

scrolling is a boolean to indicate whether we’re scrolling.

time is how long we scrolled.

speed is the scrolling speed.

direction is the scrolling direction.

position is the scrolling position.

Conclusion

React Hooks for RxJS lets us use Rxjs observables in our React app.

Scroll Data Hook lets us watch for different kinds of scrolling data in our app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *