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.

Categories
React Hooks

Top React Hooks — Update 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-use

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

useUnmount

The useUnmount hook lets us call a function when the component will unmount.

For instance, we can use it by writing:

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

export default function App() {
  useUnmount(() => console.log("umounted"));

  return <div />;
}

The callback we pass into the hook is run when the component is unmounted.

useUpdateEffect

The useUpdateEffect hook lets us run code after the component is mounted.

The signature is the same as the useEffect hook.

For instance, we can write:

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

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

  React.useEffect(() => {
    const interval = setInterval(() => {
      setCount(count => count + 1);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  useUpdateEffect(() => {
    console.log("count", count);

    return () => {
      // ...
    };
  }, [count]);

  return <div>{count}</div>;
}

We have the setInterval call in the useEffect callback.

It returns a timer so that we can call clearInterval to clear it in the function the callback returns.

The useUpdateEffect hook runs when count updates.

This means that the console log only logs the value when the component state or props updates.

We pass in an array with the values to watch for and run the callback.

useIsomorphicLayoutEffect

The useIsomorphicLayoutEffect hook is a version of the useLayoutEffect hook that doesn’t show warnings when running in a server-side rendered app.

For instance, we can write:

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

export default function App() {
  const [value] = React.useState(1);

  useIsomorphicLayoutEffect(() => {
    window.console.log(value);
  }, [value]);

  return <div>{value}</div>;
}

useDeepCompareEffect

The useDeepCompareEffect hook is an alternate version of the useEffect hook that does deep comparisons to determine whether the callback should be run.

For instance, we can write:

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

export default function App() {
  const [count, { inc }] = useCounter(0);
  const [options, setOptions] = React.useState({ step: 5 });

  useDeepCompareEffect(() => {
    inc(options.step);
  }, [options]);

  return (
    <div>
      <button onClick={() => setOptions(({ step }) => ({ step: step + 1 }))}>
        increment
      </button>
      <p>{count}</p>
    </div>
  );
}

We use the useDeepCompareEffect hook to watch for changes in the options state.

It’s an object, so we can use this hook to watch for changes and run the callback if needed instead of using useEffect .

In the callback, we call inc to increase the count state by the option.step value.

useShallowCompareEffect

The useShallowCompareEffect hook will do shallow comparison instead on each dependency instead of checking for reference equality when determining when to run the callback.

For instance, we can write:

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

export default function App() {
  const [count, { inc }] = useCounter(0);
  const [options, setOptions] = React.useState({ step: 5 });

  useShallowCompareEffect(() => {
    inc(options.step);
  }, [options]);

  return (
    <div>
      <button onClick={() => setOptions(({ step }) => ({ step: step + 1 }))}>
        increment
      </button>
      <p>{count}</p>
    </div>
  );
}

We pass in the options array to run the callback we passed into useShallowCompareEffect when it changes.

The rest of the code is the same as the previous example.

Conclusion

The react-use library have hooks that aren’t available in React itself, including varieties of useEffect .