Categories
React Hooks

Top React Hooks — Hover, Full Screen, Events, and Geolocation

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 Recipes

React Recipes comes with many hooks that we can use to do various things.

The useEventListener hook lets us listen to various events easily within our React component.

To use it, we can write:

import React, { useState, useCallback } from "react";
import { useEventListener } from "react-recipes";

export default function App() {
  const [coords, setCoords] = useState({ x: 0, y: 0 });

  const handler = useCallback(
    ({ clientX, clientY }) => {
      setCoords({ x: clientX, y: clientY });
    },
    [setCoords]
  );

  useEventListener("mousemove", handler);

  return (
    <p>
      The mouse position is ({coords.x}, {coords.y})
    </p>
  );
}

We use the useState hook to set the initial mouse coordinates.

Then we added a callback to the useCallback hook that’s used as the mousemove event listener.

Then we pass that handler to the useEventListener hook.

useEventListener takes an optional 3rd argument for the element to listen to.

The default value is window .

Then we get the mouse coordinates from the coords state.

useFullScreen is a gook that lets us determine and toggle if the screen or element is in full-screen mode.

We can use it by writing:

import React from "react";
import { useFullScreen } from "react-recipes";

export default function App() {
  const { fullScreen, toggle } = useFullScreen();

  return (
    <>
      <button onClick={toggle}>Toggle Full Screen</button>
      <p>{fullScreen.toString()}</p>
    </>
  );
}

We used the useFullScreen hook to return an object with the toggle function.

It lets us toggle full-screen mode.

It also returns the fullScreen property to indicate if the document is full screen.

open lets us open full-screen mode.

close lets us close full-screen mode.

The useGeolocation hook lets us get and watch the geolocation of a user.

To use it, we can write:

import React from "react";
import { useGeolocation } from "react-recipes";

export default function App() {
  const { latitude, longitude, timestamp, accuracy, error } = useGeolocation(
    true
  );

  return (
    <p>
      latitude: {latitude}
      longitude: {longitude}
      timestamp: {timestamp}
      accuracy: {accuracy && `${accuracy}m`}
      error: {error}
    </p>
  );
}

We use the useGeolocation with the argument true to indicate that we want to follow the location.

It also takes a second argument with some options.

We can enable high accuracy, set timeout, and set the max-age for caching.

It returns an object with the latitude, longitude, timestamp, accuracy, and error.

The useHover hook lets us know when the most is hovering over an element.

To use it, we can write:

import React from "react";
import { useHover } from "react-recipes";

export default function App() {
  const [hoverRef, isHovered] = useHover();

  return <div ref={hoverRef}>{isHovered.toString()}</div>;
}

We call the useHover hook in our component, which returns 2 things.

The hoverRef is a ref that we pass into the component we want to watch.

isHovered indicates whether we hovered over the element we’re watching.

Conclusion

React Recipes comes with hooks for helping us get geolocation data, watching hovering, toggling full screen, and more.

Categories
React Hooks

Top React Hooks — Hover, Focus, and Array

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 useInput hook lets us take care of value changes with one hook.

For instance, we can write:

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

export default function App() {
  const newTodo = useInput("");

  return (
    <div>
      <input {...newTodo.bindToInput} />
      <input {...newTodo.bind} />
      <p>{newTodo.value}</p>
    </div>
  );
}

We have 2 inputs.

They both use a property from the newTodo object returned by useInput to let us handle input value changes.

bindToInput binds the value and onChange props to an input that has e.target.value .

bind binds the value and onChange props to an input that use e in onChange .

There’s also the clear method to clear the input value.

The useFocus hook lets us detect whether an element is in focus or not.

To use it, we can write:

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

export default function App() {
  const { focused, bind } = useFocus();

  return (
    <div>
      <input {...bind} />
      <p>{focused ? "focused" : "not focused"}</p>
    </div>
  );
}

The useFocus hook returns an object with the focused and bind properties.

The bind object passed into the input so that we can watch for the focus state of the input.

Then we can get the focus state with the focused property.

The useHover hook lets us watch for the hover state of an element.

We can use it by writing:

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

export default function App() {
  const { hovered, bind } = useHover();

  return (
    <div>
      <p>{hovered ? "hovered" : "not hovered"}</p>
      <input {...bind} />
    </div>
  );
}

Like with useFocus , we pass the bind property to the input.

This way, we can watch whether the input is hovered on or not.

Then we can get the hover state with the hovered property.

The useArray hook lets us manage array state easily.

For instance, we can write:

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

export default function App() {
  const { add, clear, removeIndex, value } = useArray(["foo", "bar"]);

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

We use the useArray hook which returns takes an array for its initial value.

Then it returns an object with various properties we can use.

add lets us append an item to the array.

clear lets us empty the array.

removeIndex lets us remove an item by its index.

value has the array’s value.

It also returns the removeById property that lets us remove an item by ID.

For instance, we can write:

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

export default function App() {
  const { add, clear, removeById, value } = useArray([
    { id: 1, name: "foo" },
    { id: 2, name: "baz" }
  ]);

  return (
    <div>
      <button onClick={() => add({ id: value.length + 1, name: "qux" })}>
        add
      </button>
      <button onClick={() => clear()}>clear</button>
      <button onClick={() => removeById(value.length)}>remove by id</button>
      <p>{value.map(v => v.name).join(", ")}</p>
    </div>
  );
}

We have an array with entries that have the id property.

Then we can call removeById with the ID to remove the item by its ID.

Conclusion

React hookedUp has useful hooks for tracking hover, focus, and array states.

Categories
React Hooks

Top React Hooks — Hotkeys, Visibility, Width, and Meta Tags

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-hotkeys-hook

The react-hotkeys-hook library has a hook that lets us listen to hotkey presses.

To install it, we run:

npm install react-hotkeys-hook

or:

yarn add react-hotkeys-hook

Then we can use it by writing:

import React from "react";
import { useHotkeys } from "react-hotkeys-hook";

export default function App() {
  const [count, setCount] = React.useState(0);
  useHotkeys("ctrl+", () => setCount(prevCount => prevCount + 1));

  return <p>Pressed {count} times.</p>;
}

The useHotkeys hook lets us listen to key combo presses.

The first argument is the key combination.

The 2nd is the callback that runs when the key combo is pressed.

react-intersection-visible-hook

The react-intersection-visible-hook library lets us detect the visibility of a component.

To use it, we can install it by running:

npm i react-intersection-visible-hook

Then we can use it by writing:

import React from "react";
import useVisibility from "react-intersection-visible-hook";

export default function App() {
  const nodeRef = React.useRef(null);
  const visibility = useVisibility(nodeRef);

  return (
    <>
      <div className="App" ref={nodeRef}>
        <p style={{ position: "fixed" }}>
          {visibility.isIntersecting && visibility.isIntersecting.toString()}
        </p>
        <p>hello</p>
      </div>
    </>
  );
}

We create the ref and then pass it to the useVisibility hook.

Then we pass the ref to the ref prop to watch the div.

Then we can use it with the visible.isIntersecting property to check for the visibility of the div.

react-media-hook

The react-media-hook library lets us watch for the dimensions of the screen.

To install it, we run:

yarn add react-media-hook

or:

npm i react-media-hook --save

Then we can use it by writing:

import React from "react";
import { useMediaPredicate } from "react-media-hook";

export default function App() {
  const biggerThan300 = useMediaPredicate("(min-width: 300px)");

  return <div>{biggerThan300 && <button>click me</button>}</div>;
}

We pass the media query into the useMediaPredicate hook to watch the width of the screen.

It’ll return true if the screen width is 300px or wider.

Then we can show something given the width.

React MetaTags Hook

The React MetaTags Hook lets us add various attributes to our meta tags.

We can use it by installing it by running:

npm install react-metatags-hook

or:

yarn add react-metatags-hook

Then we can use it by writing:

import React from "react";
import useMetaTags from "react-metatags-hook";

const Page = ({ match }) => {
  const {
    params: { id },
    url
  } = match;
  useMetaTags(
    {
      title: `Page Title`,
      description: `A pahe with id: ${id}`,
      charset: "utf8",
      lang: "en",
      metas: [
        { name: "keywords", content: "foo, bar" },
        { name: "robots", content: "index, follow" },
        { name: "DC.Title", content: "Dublin Core Title" },
        { name: "url", content: `http://example.com${url}` },
        { property: "fb:app_id", content: "1234567890" },
        { "http-equiv": "Cache-Control", content: "no-cache" }
      ],
      links: [
        { rel: "canonical", href: "http://example.com" },
        { rel: "icon", type: "image/ico", href: "/favicon.ico" },
        {
          rel: "apple-touch-icon",
          sizes: "72x72",
          type: "image/png",
          href: "/apple-72.png"
        }
      ],
      openGraph: {
        title: "Page Title",
        image: "http://example.com/ogimage.jpg",
        site_name: "My Site"
      },
      twitter: {
        card: "summary",
        creator: "[@you](http://twitter.com/you "Twitter profile for @you")",
        title: "Page Title"
      }
    },
    [id, url]
  );
  return <>hello</>;
};

export default function App() {
  return (
    <div>
      <Page match={{ params: { id: 1 }, url: "example" }} />
    </div>
  );
}

We just use it by creating an object with properties that are valid meta tag attributes.

They include the title , description , charset , lang , of:* and twitter:* attributes.

We can put everything in and they’ll be added into meta tags.

Conclusion

The react-hotkeys-hook library lets us watch for hotkey presses.

react-intersection-visible-hook lets us watch for visibility of an element.

react-media-hook lets us check for various screen sizes.

React MetaTags Hook lets us add meta tags dynamically.

Categories
React Hooks

Top React Hooks — Helper 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 Pirate

React Pirate is a library with various hooks we can use.

To install it, we can run:

npm install react-pirate

or:

yarn add react-pirate

It comes with various hooks, including the usePrevious hook to get the previous value of a state.

Then we can use it by writing:

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

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

  return (
    <div>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <p>
        {count} {prevCount}
      </p>
    </div>
  );
}

The usePrevious hook lets us get the previous value of a state.

We just pass in the count hook to the usePrevious hook.

It returns the previous value of count .

The useToggle hook lets us create a boolean state and toggle it.

For instance, we can write:

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

export default function App() {
  const { value, toggle } = useToggle(false);

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

to use the useToggle hook.

The hook takes a boolean as an argument.

It’s used as the initial value.

It returns an object with the value and toggle properties.

value has the value of the boolean.

toggle lets us toggle value .

The useMount hook lets us run code when the component is mounted.

For example, we can write:

import React, { useLayoutEffect } from "react";
import { useMount } from "react-pirate";

export default function App() {
  useMount(
    () => {
      console.log("mounted");
    },
    { hook: useLayoutEffect }
  );

  return <p>hello</p>;
}

We use the useMount hook with a callback in the first argument that runs when the component is mounted.

It does similar things to the componentDidMount method.

It also comes with ane equivalent to the componentDidUpdate method.

For example, we can write:

import React from "react";
import { useUpdate } from "react-pirate";

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

  useUpdate(() => {
    console.log("updated");
  });

  return (
    <>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <p>{count}</p>
    </>
  );
}

We added the useUpdate hook with a callback that runs when the count state is updated.

It also comes with the useUnmount hook that takes a callback that runs a component unmounts.

We can use that by writing:

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

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

  return <></>;
}

react-powerhooks

The react-powerhooks library comes with various hooks that we can use in our app.

To install it, we run:

yarn add react-powerhooks

Then we can use the hooks that it comes with.

For instance, we can use the useToggle hook by writing:

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

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

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

We use the useToggle hook in our component.

It takes an argument for the initial value.

It returns an array with the value as the value variable.

toggle is the function to toggle value .

It comes with many more hooks to help us.

Conclusion

React Pirate and react-powerhooks both provide us many helper hooks.

Categories
React Hooks

Top React Hooks — Global State, Image Size, and Lifecycle

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-global-state

The react-hooks-global-state library lets us create global states for our React app easily.

To use it, we install it by running:

npm install react-hooks-global-state

Then we use it by writing:

import React from "react";
import { createGlobalState } from "react-hooks-global-state";

const initialState = { count: 0 };
const { useGlobalState } = createGlobalState(initialState);

const Counter = () => {
  const [count, setCount] = useGlobalState("count");
  return (
    <div>
      <span>Counter: {count}</span>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <button onClick={() => setCount(count => count - 1)}>decrement</button>
    </div>
  );
};

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

We create a global state with the createGlobalState function.

We pass in the initialState to it to set that as the initial state.

This returns the useGlobalState hook which has the global state.

Then we can use that with the useGlobalState hook.

We pass in the state we want to get by passing in a string.

It returns an array with the state value and the function to change it in that order.

We call setCount as we do with useState ‘s state change functions.

react-hooks-image-size

The react-hooks-image-size library has a React hook for getting the size of an image.

To install it, we run:

npm install --save @use-hooks/image-size

or

yarn add @use-hooks/image-size

Then we can use it by writing:

import React from "react";
import useImageSize from "[@use](http://twitter.com/use "Twitter profile for @use")-hooks/image-size";

export default function App() {
  const url = "https://placekitten.com/g/600/600";
  const [width, height] = useImageSize(url);

  return (
    <>
      <img src={url} width={100} height={100} alt="cat" />
      <div>
        Natural size: {width} x {height}
      </div>
    </>
  );
}

The useImageSize hook returns the image’s natural width and height.

These are the values of width and height respectively.

React Hooks Lib

React Hooks Lib is a library that has many reusable React hooks.

To install it, we can run:

npm i react-hooks-lib --save

Then we can use the hooks that come with the library.

The useDidMount hook lets us run some code when the component is mounted.

For instance, we can use it by writing:

import React from "react";
import { useDidMount } from "react-hooks-lib";

export default function App() {
  useDidMount(() => {
    console.log("mounted");
  });

  return <></>;
}

We use the useDidMount hook with a callback which runs when the component is mounted.

The useWillUnmount hook is the equivalent of the componentWillUnmount method of React class components.

The callback we pass in runs when the component will unmount.

For example, we can write:

import React from "react";
import { useWillUnmount } from "react-hooks-lib";

export default function App() {
  useWillUnmount(() => {
    console.log("will unmount");
  });

  return <></>;
}

to run the callback when the component unmounts.

Conclusion

The react-hooks-global-state library lets us create a global state in our React app.

The react-hooks-image-size library gets the natural size of the image.

React Hooks Lib is a library with a bunch of reusable hooks.