Categories
React Hooks

Top React Hooks — Scroll, Battery, and Pub/Sub

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-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 .

And y should be the same as scrollY .

react-use-trigger

The react-use-trigger package lets us implement the pub-sub pattern within our React app.

To install it, we run:

yarn add react-use-trigger

or:

npm i react-use-trigger --save

Then we can use it by writing:

import React from "react";
import createTrigger from "react-use-trigger";
import useTriggerEffect from "react-use-trigger/useTriggerEffect";

const fooTrigger = createTrigger();

const Subscriber = () => {
  useTriggerEffect(() => {
    console.log("triggered");
  }, fooTrigger);

  return <div />;
};

const Sender = () => {
  return (
    <button
      onClick={() => {
        fooTrigger();
      }}
    >
      Send
    </button>
  );
};

export default function App() {
  return (
    <>
      <Sender />
      <Subscriber />
    </>
  );
}

We have the Sender and Subscriber components to send and subscribe to triggers respectively.

Subscriber has the useTriggerEffect hook to listen to triggered events.

The callback runs when the trigger is run.

The 2nd argument is the trigger to watch for.

The Sender calls the function returned by the createTrigger to trigger the trigger.

So when we click the Send button, we’ll see 'triggered' logged.

We can use also watch the trigger with the useEffect hook.

For instance, we can write:

import React from "react";
import createTrigger from "react-use-trigger";
import useTrigger from "react-use-trigger/useTrigger";

const fooTrigger = createTrigger();

const Subscriber = () => {
  const fooTriggerValue = useTrigger(fooTrigger);

  React.useEffect(() => {
    console.log("triggered");
  }, [fooTriggerValue]);

  return <div />;
};

const Sender = () => {
  return (
    <button
      onClick={() => {
        fooTrigger();
      }}
    >
      Send
    </button>
  );
};

export default function App() {
  return (
    <>
      <Sender />
      <Subscriber />
    </>
  );
}

We have our trigger fooTrigger .

And we pass that to the useTrigger hook.

And we can watch the returned value with the useEffect hook.

react-use

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

To use it, we install it by running:

npm i react-use

It comes with many hooks.

We can use the useBattery gook to track the battery state of our device.

For example, we can write:

import React from "react";
import { useBattery } from "react-use";

export default function App() {
  const batteryState = useBattery();

  if (!batteryState.isSupported) {
    return (
      <div>
        <b>Battery sensor</b>: <span>not supported</span>
      </div>
    );
  }

  if (!batteryState.fetched) {
    return (
      <div>
        <b>Battery state</b>: <span>fetching</span>
      </div>
    );
  }

  return (
    <div>
      <b>Charge level</b>:<span>{(batteryState.level * 100).toFixed(0)}%</span>{" "}
      <br />
      <b>Charging</b>:<span>{batteryState.charging ? "yes" : "no"}</span> <br />
      <b>Charging time</b>:
      <span>
        {batteryState.chargingTime ? batteryState.chargingTime : "finished"}
      </span>
      <br />
      <b>Discharging time</b>:<span>{batteryState.dischargingTime}</span>
    </div>
  );
}

to display all the information about our battery.

It has data about the level, whether it’s charging or not, has it finished charging, and discharging time.

Conclusion

react-use-scroll-position is a useful hook to let us watch the scroll position.

react-use-trigger lets us implement the pub-sub pattern with ease.

react-use is a useful library with many hooks, including a battery status hook.

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 *