Categories
React Hooks

Top React Hooks — State, Arrays, and Observables

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

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

useObservable

The useObservable hook lets us get the latest value of an observable.

To use it, we can write:

import React from "react";
import { useObservable } from "react-use";
import { BehaviorSubject } from "rxjs";

const counter$ = new BehaviorSubject(0);

export default function App() {
  const value = useObservable(counter$, 0);

  return (
    <button onClick={() => counter$.next(value + 1)}>Clicked {value}</button>
  );
}

We installed Rxjs so that we can use the BehaviorSubject function to return an observable.

Then we pass that into the useObservable function to return the value from the observable.

We can use the next method from the counter$ observable to update its value.

useRafState

To update the state in the callback of requestAnimationFrame , we can use the useRafState hook.

For instance, we can use it by writing:

import React from "react";
import { useRafState, useMount } from "react-use";

export default function App() {
  const [state, setState] = useRafState({
    width: 0,
    height: 0
  });

  useMount(() => {
    const onResize = () => {
      setState({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener("resize", onResize);

    return () => {
      window.removeEventListener("resize", onResize);
    };
  });

  return <pre>{JSON.stringify(state, null, 2)}</pre>;
}

We add the useRafState hook with the object holding the initial value as the argument.

Then we use useMount to attach the window listeners for the resize event.

We update th width and height of it as the window resizes.

useSetState

The useSetState hook provides us with a way to set the state as we did with setState in class components.

For example, we can write:

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

export default function App() {
  const [state, setState] = useSetState({});

  return (
    <div>
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <button onClick={() => setState({ name: "james" })}>set name</button>
      <button onClick={() => setState({ foo: "bar" })}>foo</button>
      <button
        onClick={() => {
          setState(prevState => ({
            count: (prevState.count || 0) + 1
          }));
        }}
      >
        count
      </button>
    </div>
  );
}

We called the useSetState hook to return the state and setState variables.

state has the state.

And setState lets us set the state as we did with setState in class components.

It can take an object or a callback that has the previous state as the parameter and return the new state,

useStateList

The useStateList hook lets us iterate over state lists.

For instance, we can write:

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

const stateSet = ["foo", "bar", "baz"];

export default function App() {
  const {
    state,
    prev,
    next,
    setStateAt,
    setState,
    currentIndex
  } = useStateList(stateSet);
  const indexInput = React.useRef(null);
  const stateInput = React.useRef(null);

  return (
    <div>
      <pre>
        {state} [index: {currentIndex}]
      </pre>
      <button onClick={() => prev()}>prev</button>
      <br />
      <button onClick={() => next()}>next</button>
      <br />
      <input type="text" ref={indexInput} />
      <button onClick={() => setStateAt(indexInput.current.value)}>
        set state by index
      </button>
      <br />
      <input type="text" ref={stateInput} />
      <button onClick={() => setState(stateInput.current.value)}>
        set state by value
      </button>
    </div>
  );
}

We called the useStateList hook with an array and it returns various properties.

state has the array state,

prev is a function to set the state and currentIndex to the previous entry’s value and index.

next is a function to set the state and currentIndex return the next entry’s value and index.

setStateAt lets us get the value by index and set that as the state and currentIndex ‘s value.

And setState takes the entry’s content and returns the state and currentIndex ‘s value for that.

Conclusion

The react-use library has hooks to let us use observables, set state, and traverse arrays.

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 *