Categories
React Hooks

Top React Hooks — Observables and Hooks

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.

Categories
React Hooks

Top React Hooks — Forms and Forward Refs

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.

useMethods

The useMethods hook is a simpler useReducer hook implementation.

It lets us cache states so it’s useful for using complex computations.

For instance, we can write:

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

const initialState = {
  count: 0
};

function countMethods(state) {
  return {
    reset() {
      return initialState;
    },
    increment() {
      return { ...state, count: state.count + 1 };
    },
    decrement() {
      return { ...state, count: state.count - 1 };
    }
  };
}

export default function App() {
  const [state, methods] = useMethods(countMethods, initialState);

  return (
    <>
      <p>{state.count}</p>
      <button onClick={methods.increment}>increment</button>
      <button onClick={methods.decrement}>decrement</button>
      <button onClick={methods.reset}>reset</button>
    </>
  );
}

We created the countMethods function with the methods we can use to manipulate our state .

It returns the state as we want to by returning an object with various methods.

reset returns the initial state.

increment returns a state with count increased by 1.

decrement returns a state with count decreased by 1.

We passed the countMethods function into the useMethods hook along with the initialState .

Then that returns the state and the methods object that has the methods returned by countMethods .

We then called them when we click the buttons.

useEnsuredForwardedRef

The useEnsuredForwardedRef hook letrs us forward refs to a child component.

For instance, we can write:

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

const Foo = React.forwardRef((props, ref) => {
  const ensuredForwardRef = useEnsuredForwardedRef(ref);

  React.useEffect(() => {
    console.log(ensuredForwardRef.current);
  }, []);

  return <div ref={ensuredForwardRef} />;
});

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

to use the hook.

We just pass in a ref to the useEnsuredForwardRef hook and it’ll return ensuredForwardRef .

It’ll never be undefined , so we can use it as we do in the useEffect callback.

useFormless

React-useFormless is a simple library that lets us create forms with a simple hook.

We can install it by running:

yarn add react-useformless

or

npm install react-useformless

Then we can use it by writing:

import React from "react";
import useFormless from "react-useformless";

const options = {
  initialValues: {
    name: "",
    password: ""
  },
  validate: (name, value) => {
    const validators = {
      name: name => (name.length > 0 ? "" : "name is requred"),
      password: password => (password.length > 0 ? "" : "password is required")
    };

const errorFn = validators[name];
    return errorFn(value);
  },
  onError: (ev, { values, errors }) => {
    ev.preventDefault();
  },
  onSuccess: (ev, { values }) => {
    ev.preventDefault();
  },
  onSubmit: ev => {
    ev.preventDefault();
    console.log(ev);
  }
};

export default function App() {
  const { values, errors, inputProps, onSubmit } = useFormless(options);

 return (
    <section>
      <form onSubmit={onSubmit}>
        <div>
          <label htmlFor="name">name</label>
          <input
            id="name"
            type="text"
            {...inputProps("name")}
            value={values.name}
          />
          <p>{errors.name}</p>
        </div>
        <div>
          <label htmlFor="password">password</label>
          <input
            id="password"
            type="password"
            {...inputProps("password")}
            value={values.password}
          />
          <p>{errors.password}</p>
        </div>
        <input type="submit" value="Login" />
      </form>
    </section>
  );
}

We have the options object with the options.

initialValues has the initial values of the form.

validate is a function that returns an error object after validation.

The returned object should have the keys with the input names and values being the error message.

onError , onSuccess and onSubmit are handlers that are run when those events are emitted.

We pass in the whole object to the useFormless hook.

It returns an object with the variables we can use in our form.

inputProps pass in the input elements.

onSubmit is the submit handler.

errors has the error messages.

values has the input values for each field.

Conclusion

React-use is a versatile hooks library.

React-useFormless lets us create forms easily with our React app.

Categories
React Hooks

Top React Hooks — Data Types

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.

useToggle

The useToggle hook lets us create a boolean state that we can toggle with a function.

To use it, we can write:

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

export default function App() {
  const [on, toggle] = useToggle(true);

  return (
    <div>
      <div>{on.toString()}</div>
      <button onClick={toggle}>toggle</button>
      <button onClick={() => toggle(true)}>true</button>
      <button onClick={() => toggle(false)}>false</button>
    </div>
  );
}

useToggle takes an argument for the initial value of the toggle.

It returns the on state with the boolean.

And toggle lets us toggle the value or set on with a specific value.

useCounter

The useCounter hook lets us create a numeric state with functions to set or reset the value.

For instance, we can write:

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

export default function App() {
  const [val, { inc, dec, set, reset }] = useCounter(1);

  return (
    <div>
      <div>{val}</div>
      <button onClick={() => inc()}>Increment</button>
      <button onClick={() => dec()}>Decrement</button>
      <button onClick={() => reset()}>Reset</button>
      <button onClick={() => set(100)}>Set 100</button>
    </div>
  );
}

We call the useCounter hook to return an array with various things.

The argument is the initial value.

val has the current value of the number state.

inc is the function to increment val .

dec is the function to decrement val .

set is the function to set val to a specific value.

reset resets val to the initial value.

We can also set the maximum and minimum values that val can take.

For example, we can write:

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

export default function App() {
  const [val, { inc, dec, set, reset }] = useCounter(1, 10, 1);

  return (
    <div>
      <div>{val}</div>
      <button onClick={() => inc()}>Increment</button>
      <button onClick={() => dec()}>Decrement</button>
      <button onClick={() => reset()}>Reset</button>
      <button onClick={() => set(9)}>Set 9</button>
    </div>
  );
}

The 2nd argument of useCounter is the maximum value of val .

The 3rd argument is the minimum value of val that it can take.

useList

The useList hook lets us create a state from an array and manipulate it.

To use it, we can write:

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

export default function App() {
  const [
    list,
    {
      set,
      push,
      updateAt,
      insertAt,
      update,
      updateFirst,
      upsert,
      sort,
      filter,
      removeAt,
      clear,
      reset
    }
  ] = useList([1, 2, 3, 4, 5]);

  return (
    <div>
      <button onClick={() => set([1, 2, 3])}>Set to [1, 2, 3]</button>
      <button onClick={() => push(Math.floor(100 * Math.random()))}>
        Push
      </button>
      <button onClick={() => updateAt(1, Math.floor(100 * Math.random()))}>
        Update
      </button>
      <button onClick={() => removeAt(1)}>Remove index 1</button>
      <button onClick={() => filter(item => item % 2 === 0)}>
        Filter even values
      </button>
      <button onClick={() => sort((a, b) => a - b)}>Sort ascending</button>
      <button onClick={() => sort((a, b) => b - a)}>Sort descending</button>
      <button onClick={clear}>Clear</button>
      <button onClick={reset}>Reset</button>
      <pre>{JSON.stringify(list, null, 2)}</pre>
    </div>
  );
}

We call the useList hook with an initial array as the argument.

It returns an object with various properties and the array itself.

list has the value of the array.

set lets us set the array to a different array.

push lets us append an entry to the list array.

insertAt lets us insert an element to the list array.

update lets us update a list entry.

updateFirst updates the first entry of list.

upsert lets us insert or update an entry of list.

sort lets us sort our the list array.

filter filters the the list array.

removeAt removes a list entry with the given index.

clear empties the list array.

reset resets the list array to the initial value.

Conclusion

The react-use library lets us create a toggle, number, and list state we can manipulate easily.

Categories
React Hooks

Top React Hooks — Data Structures

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.

useMap

The useMap hook lets us track key-value pairs.

To use it, we can write:

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

export default function App() {
  const [map, { set, setAll, remove, reset }] = useMap({
    hello: "world"
  });

  return (
    <div>
      <button onClick={() => set(String(Date.now()), new Date().toString())}>
        Add
      </button>
      <button onClick={() => reset()}>Reset</button>
      <button onClick={() => setAll({ foo: "bar" })}>Set new data</button>
      <button onClick={() => remove("foo")} disabled={!map.foo}>
        Remove 'hello'
      </button>
      <pre>{JSON.stringify(map, null, 2)}</pre>
    </div>
  );
}

The useMap hook takes an object and returns an array that has the state object and another object with methods to let us modify the state object.

map has the map state object itself

set takes a key and value as arguments and put them into map .

setAll lets overwrite the existing value of map with another one.

remove lets us remove a property with a given key from map .

reset will reset the state object to the initial value, which is what we passed into the useMap hook.

useSet

The useSet hook lets us get and manipulate a set.

We can add things if they don’t exist.

For instance, we can write:

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

export default function App() {
  const [set, { add, has, remove, toggle, reset }] = useSet(new Set(["bar"]));

  return (
    <div>
      <button onClick={() => add(String(Date.now()))}>Add</button>
      <button onClick={() => reset()}>Reset</button>
      <button onClick={() => remove("foo")} disabled={!has("foo")}>
        Remove 'hello'
      </button>
      <button onClick={() => toggle("foo")}>toggle foo</button>
      <pre>{JSON.stringify([...set], null, 2)}</pre>
    </div>
  );
}

We have the useSet hook with a set passed in to set the initial value of the returned set.

It returns an array with 2 entries.

The first is the set , which is the set itself.

The 2nd is an object with various methods to change the set.

add lets us add an item to the set.

has lets us check whether something is in the set.

remove lets us remove an item from the set.

toggle lets us toggle on an off an item in the set.

reset resets the set to the initial value.

useQueue

We can use the useQueue hook to create a simple FIFO queue.

For example, we can write:

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

export default function App() {
  const { add, remove, first, last, size } = useQueue();

  return (
    <div>
      <ul>
        <li>first: {first}</li>
        <li>last: {last}</li>
        <li>size: {size}</li>
      </ul>
      <button onClick={() => add(Math.random())}>Add</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
}

to create a queue and use it.

The useQueue hook returns an object with various properties.

The add function lets us add an entry to the queue.

remove lets us remove the last entry from the queue.

first returns the first entry of the queue.

last returns the last entry of the queue.

size returns the size of the queue.

Conclusion

React-use lets us create states with various data structures, including maps, sets, and queues.

Categories
React Hooks

Top React Hooks — Vibration, Videos, and Intervals

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.

useVibrate

The useVibrate hook lets us vibrate our device on any device that’s capable of this.

For instance, we can use it by writing:

import React from "react";
import { useToggle, useVibrate } from "react-use";

export default function App() {
  const [vibrating, toggleVibrating] = useToggle(false);

  useVibrate(vibrating, [360, 120, 260, 110, 1420, 300], false);

  return (
    <div>
      <button onClick={toggleVibrating}>
        {vibrating ? "Stop" : "Vibrate"}
      </button>
    </div>
  );
}

We have the useToggle hook to toggle the vibration.

The useVibrate hook takes the vibrating state that we created earlier.

The array has the array with the magnitude of the vibrations in each entry.

The 3rd argument indicates whether we want to loop or not.

useVideo

The useVideo hook lets us create a video element with controls.

To use it, we write:

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

export default function App() {
  const [video, state, controls, ref] = useVideo(
    <video
      src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4"
      autoPlay
    />
  );

  return (
    <div>
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <button onClick={controls.pause}>Pause</button>
      <button onClick={controls.play}>Play</button>
      <button onClick={controls.mute}>Mute</button>
      <button onClick={controls.unmute}>Un-mute</button>
      <button onClick={() => controls.volume(0.1)}>Volume: 10%</button>
      <button onClick={() => controls.volume(0.5)}>Volume: 50%</button>
      <button onClick={() => controls.volume(1)}>Volume: 100%</button>
      <button onClick={() => controls.seek(state.time - 5)}>-5 sec</button>
      <button onClick={() => controls.seek(state.time + 5)}>+5 sec</button>
      {video}
    </div>
  );
}

to use the hook.

The useVideo takes a component for rendering the video.

And it returns an array with various variables.

video has the video player component itself.

state has the video playing state.

The state has the time which is the time that the video is at.

duration has the duration of the video.

paused indicates whether the video is paused or not.

muted indicates whether the video is muted or not.

controls has the method to let us control the video.

useRaf

The useRaf hook lets us force a component to render on each requestAnimationFrame .

It returns the percentage of time elapsed.

To use it, we can write:

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

export default function App() {
  const elapsed = useRaf(15000, 1000);

  return <div>Elapsed: {elapsed}</div>;
}

We have the useRaf hook with 2 arguments.

The first is the animation duration.

The 2nd is the delay after which to start re-rendering the component.

They’re both in milliseconds.

useInterval

The useInterval hook lets us run a piece of code periodically.

To use it, we can write:

import React from "react";
import { useInterval, useBoolean } from "react-use";

export default function App() {
  const [count, setCount] = React.useState(0);
  const [isRunning, toggleIsRunning] = useBoolean(true);

  useInterval(
    () => {
      setCount(count + 1);
    },
    isRunning ? 1000 : null
  );

  return (
    <div>
      <h1>count: {count}</h1>
      <div>
        <button onClick={toggleIsRunning}>
          {isRunning ? "stop" : "start"}
        </button>
      </div>
    </div>
  );
}

We use the useInterval hook with 2 arguments.

The callback that runs periodically is the first argument.

The 2nd argument is the length between each callback call.

If it’s null , then the callback isn’t run.

Conclusion

The react-use library lets us run code periodically, re-render during each requestAnimationFrame call, vibrate our device, and display videos.