Categories
React Hooks

Top React Hooks — Outside Clicks and Dimensions

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 Cool Dimensions

React Cool Dimensions lets us watch the dimension of a component.

To use it, we install it by running:

yarn add react-cool-dimensions

or

npm install --save react-cool-dimensions

Then we can use it by writing:

import React from "react";
import useDimensions from "react-cool-dimensions";

export default function App() {
  const { ref, ...dimensions } = useDimensions({
    onResize: ({ width, height, entry, unobserve, observe }) => {
      //...
    }
  });
  return (
    <div className="App">
      <div ref={ref}>{JSON.stringify(dimensions)}</div>
    </div>
  );
}

We use the useDimensions hook which returns the ref that we can assign to the element we want to watch the size for.

Then dimensions has the object with width and height of the element we’re watching.

onResize is a method that runs when we resize the element.

We can also assign breakpoints so the hook can determine the breakpoint when watching the element size.

For instance, we can write:

import React from "react";
import useDimensions from "react-cool-dimensions";

export default function App() {
  const { ref, ...dimensions } = useDimensions({
    breakpoints: { XS: 0, SM: 320, MD: 480, LG: 640 },
    onResize: ({ currentBreakpoint }) => {
      console.log(currentBreakpoint);
    }
  });
  return (
    <div className="App">
      <div ref={ref}>{JSON.stringify(dimensions)}</div>
    </div>
  );
}

We added the breakpoints property to get the breakpoints according to what we assigned.

All the dimensions are in pixels.

We can include the border size with the measurement.

For instance, we can write:

import React from "react";
import useDimensions from "react-cool-dimensions";

export default function App() {
  const { ref, ...dimensions } = useDimensions({
    useBorderBoxSize: true
  });
  return (
    <div className="App">
      <div
        ref={ref}
        style={{
          border: "5px solid grey"
        }}
      >
        {JSON.stringify(dimensions)}
      </div>
    </div>
  );
}

Then the border is included with the measurements.

To throttle the watching, we can throttle the onResize callback calls with the Lodash throttle method.

We can also create our own ref and pass it into the useDimensions hook’s object argument’s ref property.

React Cool Onclickoutside

React Cool Onclickoutside lets us detect clicks outside an element.

To install it, we run:

yarn add react-cool-onclickoutside

or:

npm install --save react-cool-onclickoutside

Then we can use it by writing:

import React from "react";
import useOnclickOutside from "react-cool-onclickoutside";

export default function App() {
  const [openMenu, setOpenMenu] = React.useState(false);
  const ref = useOnclickOutside(() => {
    setOpenMenu(false);
  });

  const handleClickBtn = () => {
    setOpenMenu(!openMenu);
  };

  return (
    <div>
      <button onClick={handleClickBtn}>Button</button>
      {openMenu && <div ref={ref}>Menu</div>}
    </div>
  );
}

useOnclickOutside is the hook that comes with the package to detect clicks outside an element.

It returns a ref which we can pass into the ref prop of the element we want to watch the clicks outside for.

Now when we click outside the menu div, the menu will disappear.

Conclusion

React Cool Dimensions lets us watch the dimensions of our elements.

React Cool Onclickoutside lets us detect clicks that are outside an element.

Categories
React Hooks

Top React Hooks — Online Status, Timers, and Previous State

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 hookedUp

React hookedUp is a library with many hooks to make our lives easier.

To install it, we run:

npm install react-hookedup --save

or:

yarn add react-hookedup

The useMergeState lets us set the state as we did with setState in React class components.

For instance, we can use it by writing:

import React from "react";
import { useMergeState } from "react-hookedup";

export default function App() {
  const { state, setState } = useMergeState({ loading: false });

  return (
    <div>
      <button onClick={() => setState({ loading: !state.loading })}>
        toggle
      </button>
      <p>{state.loading.toString()}</p>
    </div>
  );
}

We have the useMergeState to let us manage object states easily.

It returns an object with the state and setState properties.

state has the current state value.

setState is the function to set the state.

We use it by passing in an object with the property and value.

The usePrevious hook lets us get the previous value from the useState hook.

For instance, we can write:

import React from "react";
import { usePrevious } from "react-hookedup";

export default function App() {
  const [count, setCount] = React.useState(0);
  const prevCount = usePrevious(count);
  return (
    <>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <p>
        Now: {count}, before: {prevCount}
      </p>
    </>
  );
}

We use the usePrevious hook by passing in the state value into it.

Then we can get the previous value with the value returned by the hook.

The useInterval hook lets us run setInterval the React way.

For instance, we can write:

import React from "react";
import { useInterval } from "react-hookedup";

export default function App() {
  const [count, setCount] = React.useState(0);
  useInterval(() => setCount(count => count + 1), 1000);

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

We used the useInterval hook with a callback that’s called every second as we specified in the 2nd argument.

The number is in milliseconds.

Then count is updated every second.

The useTimeout hook lets us run setTimeout with a convenient hook.

For example, we can write:

import React from "react";
import { useTimeout } from "react-hookedup";

export default function App() {
  useTimeout(() => alert("hello world"), 1500);

  return (
    <>
      <p>hello</p>
    </>
  );
}

The useTimeout hook takes a callback which runs after the time given in the 2nd argument.

The number is in milliseconds.

The useOnlineStatus hook lets us get the current online status.

For instance, we can use it by writing:

import React from "react";
import { useOnlineStatus } from "react-hookedup";

export default function App() {
  const { online } = useOnlineStatus();

  return <h1>{online ? "online" : "offline"}</h1>;
}

We just call the hook and that returns an object with the online property.

It indicates whether our app is online or not.

Conclusion

React hookedUp has many useful hooks.

We can set the previous state, use timers, and get online status with the provided hooks.

Categories
React Hooks

Top React Hooks — Mouse, Keyboard, and States

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

The react-hanger library comes with various hooks we can use to do various things.

To install it, we run:

yarn add react-hanger

The usePrevious hook lets us get the previous value from the useState hook.

For instance, we can write:

import React from "react";
import { usePrevious } from "react-hanger";

export default function App() {
  const [count, setCount] = React.useState(0);
  const prevCount = usePrevious(count);
  return (
    <>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <p>
        Now: {count}, before: {prevCount}
      </p>
    </>
  );
}

Then we have the count state with the setCount function returned from useState .

Then we pass the count state into the usePrevious hook to get the previous value of the count state returned.

React Mighty Mouse

React Mighty Mouse is a library with a hook that lets us track the mouse position.

To install it, we can run:

npm install react-hook-mighty-mouse

Then we can use it by writing:

import React from "react";
import useMightyMouse from "react-hook-mighty-mouse";

export default function App() {
  const { position } = useMightyMouse();
  return (
    <div>
      x:{position.client.x} y:{position.client.y}
    </div>
  );
}

We use the useMightyMouse hook to get an object with the position property.

Then we can get the mouse position as we move it with the client.x and client.y properties to get the x and y coordinates respectively.

react-hook-mousetrap

The react-hook-mousetrap library lets us watch for presses of a keyboard key combination.

We install it by running:

npm i react-hook-mousetrap

Then we can use it by writing:

import React from "react";
import useMousetrap from "react-hook-mousetrap";

export default function App() {
  useMousetrap(
    "ctrl+enter", () => {
      console.log("ctrl+enter pressed");
    }
  );

  return <div />;
}

We use the useMousetrap hook with the first argument being the key combination we want to track.

And the 2nd argument is the callback to run when the key combination is pressed.

React hookedUp

React hookedUp is a library with many hooks to make our lives easier.

To install it, we run:

npm install react-hookedup --save

or:

yarn add react-hookedup

Then we can start using various hooks that it comes with.

It comes with the useArray hook to let us manipulate arrays easily.

For instance, we can write:

import React from "react";
import { useArray } from "react-hookedup";

export default function App() {
  const { add, clear, removeIndex, value: currentArray } = useArray([
    "cat",
    "dog",
    "bird"
  ]);

  return (
    <>
      <button onClick={() => add("moose")}>add</button>
      <button onClick={() => clear()}>clear</button>
      <button onClick={() => removeIndex(currentArray.length - 1)}>
        remove index
      </button>
      <p>{currentArray.join(", ")}</p>.
    </>
  );
}

We have the useArray hook with the initial array as the value.

Then it returns the add , clear , and removeIndex methods to let us manipulate the array.

value has the current value.

add lets us append an entry.

clear clears the array.

removeIndex removes an item by its index.

Conclusion

The react-hanger and React hookedUp libraries comes with many hooks to help us manage states.

React Mighty Mouse and react-hook-mousetrap lets us watch for mouse position changes and key combo presses respectively.

Categories
React Hooks

Top React Hooks — Modals and Visibility

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-use-modal

The react-hooks-use-modal library lets us create a modal with ease.

To install it, we run:

npm i react-hooks-use-modal

Then we can use it by writing:

import React from "react";
import useModal from "react-hooks-use-modal";

export default function App() {
  const [Modal, open, close, isOpen] = useModal("root", {
    preventScroll: true
  });
  return (
    <div>
      <p>{isOpen ? "Yes" : "No"}</p>
      <button onClick={open}>OPEN</button>
      <Modal>
        <div>
          <h1>Title</h1>
          <p>hello world.</p>
          <button onClick={close}>CLOSE</button>
        </div>
      </Modal>
    </div>
  );
}

We use the useModal hook with some arguments.

The first argument is the ID of the element the modal attaches to.

The 2nd argument has some options.

preventScroll prevents the body from being scrolled when it’s set to true .

Then we can use the array of things it returns.

Modal has the modal component.

open is the function to open the modal.

close is the function to close the modal.

isOpen has the state to indicate whether the modal is open or not.

react-hooks-visible

The react-hooks-visible library provides us with a hook to detect the visibility of an element.

It uses the Observer API to detect the visibility of the element.

The install it, we run:

yarn add react-hooks-visible

Then we can use it by writing:

import React from "react";
import { useVisible } from "react-hooks-visible";

export default function App() {
  const [targetRef, visible] = useVisible();
  return (
    <div ref={targetRef}>
      <p style={{ position: "fixed" }}>{visible * 100} % visible</p>
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We use the useVisible hook to return the targetRef , which we pass into the ref prop of the element we want to watch.

visible returns the percent of the element that’s visible.

It’s updated as the visibility percentage changes.

We can also pass an argument into the hook to format the number.

For instance, we can write:

import React from "react";
import { useVisible } from "react-hooks-visible";

export default function App() {
  const [targetRef, visible] = useVisible(vi => (vi * 100).toFixed(2));
  return (
    <div ref={targetRef}>
      <p style={{ position: "fixed" }}>{visible} % visible</p>
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

to round the visible number to 2 decimal places.

We can also return something other than a number.

For example, we can write:

import React from "react";
import { useVisible } from "react-hooks-visible";

export default function App() {
  const [targetRef, isVisible] = useVisible(vi => vi > 0.5);
  return (
    <div ref={targetRef}>
      <p style={{ position: "fixed" }}>{isVisible.toString()} </p>
      {Array(10)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We have a callback that returns a boolean expression which compares the visibility decimal to 0.5.

isVisible would be a boolean to indicate whether the element is more than half visible.

Conclusion

The react-hooks-use-modal library lets us create a modal easily.

The react-hooks-visible lets us watch for the visibility of an element.

Categories
React Hooks

Top React Hooks — Managing States

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

The react-hanger library comes with various hooks we can use to do various things.

To install it, we run:

yarn add react-hanger

We can use the useArray hook to manipulate arrays easily.

For example, we can write:

import React from "react";
import { useArray } from "react-hanger";

export default function App() {
  const todos = useArray(["eat", "drink", "sleep"]);

  return (
    <>
      <button onClick={() => todos.push("new task")}>push new task</button>
      <button onClick={() => todos.unshift("new task")}>
        unshift new task
      </button>
      <button onClick={() => todos.pop()}>pop new task</button>
      <p>{todos.value.join(", ")}</p>
    </>
  );
}

The useArray hook returns an object with various methods for changing the array.

It also returns the value property with the state of the array.

We call the push method to append something to the array.

unshift adds an item to the beginning of the array.

pop removes an item from the end of the array.

It also has the useStateful hook to let us set a state.

For example, we can write:

import React from "react";
import { useStateful } from "react-hanger";

export default function App() {
  const toggle = useStateful(true);

  return (
    <>
      <button onClick={() => toggle.setValue(!toggle.value)}>toggle</button>
      <p>{toggle.value.toString()}</p>
    </>
  );
}

We use the useStateful hook as we do with the useState hook.

The useMap hook let us hold a map as a state and manipulate it.

For instance, we can write:

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

export default function App() {
  const { value, set, delete: del, clear } = useMap([["key", "value"]]);

 return (
    <>
      <button onClick={() => set("foo", "bar")}>add entry</button>
      <button onClick={() => del("foo")}>delete entry</button>
      <button onClick={() => clear()}>clear</button>
      <p>{value}</p>
    </>
  );
}

We use the useMap hook.

We passed an array to it with the key and value of the map.

Then it returns the value and various methods we can use to manipulate the map.

set adds an entry by passing in the key and value.

delete lets us delete an entry with the given key,

clear clears the map.

We can also pass a Map instance into the hook and get the same result.

The useSetState hook lets us manage our state as we did with the setState method in React class components.

To use it, we can write:

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

export default function App() {
  const { state, setState, resetState } = useSetState({ loading: false });

  return (
    <>
      <button onClick={() => setState({ loading: !state.loading })}>
        set state
      </button>
      <button onClick={() => resetState()}>reset state</button>
      <p>{JSON.stringify(state)}</p>
    </>
  );
}

The useSetState hook takes an object with the states we want to manage.

The argument is the initial state.

It returns the state with all the states.

setState lets us set the state as we do with setState in React class components.

resetState will reset the state to the initial state.

Conclusion

The react-hanger library comes with many useful hooks to manage various kinds of states.