Categories
React Hooks

Top React Hooks — Debounce, Error, Favicon, and Local Storage

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.

useDebounce

The useDebounce hook lets us denounce our callbacks by our give number of milliseconds.

For instance, we can write:

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

export default function App() {
  const [val, setVal] = React.useState("");
  const [debouncedValue, setDebouncedValue] = React.useState("");

  const [, cancel] = useDebounce(
    () => {
      setDebouncedValue(val);
    },
    2000,
    [val]
    );

  return (
    <div>
      <input
        type="text"
        value={val}
        placeholder="Debounced input"
        onChange={({ currentTarget }) => {
          setVal(currentTarget.value);
        }}
      />
      <div>
        <p>Debounced value: {debouncedValue}</p>
        <button onClick={cancel}>Cancel debounce</button>
      </div>
    </div>
  );
}

We call the useDebounce hook with a callback to set the debounced value in the callback.

The 2nd argument is the number of milliseconds to debounce.

The 3rd is an array with the values to watch for and call the callback when they change.

It’ll be debounced by the delay in the 2nd argument.

The hook returns an array with the cancel function to cancel the debouncing.

useError

The useError hook lets us throw errors in our code.

It’ll be caught with the ErrorBoundary component is we wrap our component with it.

For instance, we can write:

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

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>error.</h1>;
    }

    return this.props.children;
  }
}

const Foo = () => {
  const dispatchError = useError();

  const clickHandler = () => {
    dispatchError(new Error("error!"));
  };

  return <button onClick={clickHandler}>Click me to throw</button>;
};

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

We create the ErrorBoundary component with methods to log the error.

The getDerivedStateFromError function runs to return the state when an error occurs.

componenrDidCatch catches the error.

The Foo component uses the useError hook, which returns the dispatchError function that takes an Error instance.

This lets us throw an error and catch it with the ErrorBoundary component.

useFavicon

The useFavicon hook lets us set the favicon of the page.

For instance, we can write:

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

export default function App() {
  useFavicon("https://api.faviconkit.com/aws.amazon.com/144");

  return <div />;
}

We just call the useFavicon hook with the URL of the favicon change our app to that favicon.

useLocalStorage

To manage local storage, we can use the useLocalStorage hook.

It returns an array with the value, a function to set the value, and a function to remove the item.

The argument it takes is the key of the local storage item.

To use it, we can write:

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

export default function App() {
  const [value, setValue, remove] = useLocalStorage("something", "foo");

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue("qux")}>qux</button>
      <button onClick={() => setValue("baz")}>baz</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
}

In the code above, 'something' is the key.

value is the value of 'something' .

setValue sets the value of 'something' .

And remove removed the entry with key 'something' .

setValue takes an argument with the value to save.

Conclusion

The react-use library lets us denounce our code, throw errors, save to local storage, and change favicons.

Categories
React Hooks

Top React Hooks — Async, Clipboard, and Cookie

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.

useAsyncRetry

The useAsyncRetry hook lets us run async cod with an addition rety method to let us retry or refresh the async function.

To use it, we run:

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

export default function App() {
  const state = useAsyncRetry(async () => {
    const response = await fetch("https://api.agify.io/?name=michael");
    const result = await response.json();
    return result;
  }, []);

  return (
    <div>
      <button onClick={() => state.retry()}>load</button>
      {(() => {
        if (state.loading) {
          return <div>Loading...</div>;
        }

        if (state.error) {
          return <div>Error</div>;
        }

        return <div>{JSON.stringify(state.value)}</div>;
      })()}
    </div>
  );
}

The useAsyncRetry hook takes a callback that gets data from an API.

A promise is returned and it resolves to the response body.

The state is returned by the hook.

It has the retry method to let us get the data again.

Also, it has the loading and error properties to get the loading state and error respectively.

value has the response body.

useBeforeUnload

The useBeforeUnload hook lets us show a browser alert when the user tries to reload or close the page.

To use it, we can write:

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

export default function App() {
  useBeforeUnload(true, "You sure you want to leave");

  return <div />;
}

We pass in true to the first argument to enable the alert when we leave.

Then we add a string to show the content.

Most browsers don’t let us show custom text in the alert, so we can put in anything.

useCookie

useCookie is a hook that lets us return the current value of a cookie.

It also lets us update and delete the cookie.

For instance, we can use it by writing:

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

export default function App() {
  const [value, updateCookie, deleteCookie] = useCookie("count-cookie");
  const [counter, setCounter] = React.useState(1);

  React.useEffect(() => {
    deleteCookie();
  }, []);

  const updateCookieHandler = () => {
    updateCookie(counter);
    setCounter(c => c + 1);
  };

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={updateCookieHandler}>Update Cookie</button>
      <br />
      <button onClick={deleteCookie}>Delete Cookie</button>
    </div>
  );
}

We call the useCookie hook with the key of the cookie to let us get, set, and delete the cookie.

value has the value.

updateCookie is a function to let us update the cookie.

deleteCookie lets us delete the cookie.

Then we used that in the useEffect callback to clear the cookie on load.

And we used updateCookie when we click the Update Cookie button.

useCopyToClipboard

The useCopyToClipboard hook lets us copy text in a string to the clipboard.

For instance, we can use it by writing:

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

export default function App() {
  const [text, setText] = React.useState("");
  const [state, copyToClipboard] = useCopyToClipboard();

  return (
    <div>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button type="button" onClick={() => copyToClipboard(text)}>
        copy text
      </button>
      {state.error ? (
        <p>{state.error.message}</p>
      ) : (
        state.value && <p>Copied {state.value}</p>
      )}
    </div>
  );
}

We called the useCopyToClipboard hook to return the state and copyToClipboard variables.

state is the state of the clipboard.

copyToClipboard lets us copy the text we pass into it to the clipboard.

Conclusion

The react-use library provides us with hooks to copy data to the clipboard, create cookies, and run promises.

Categories
React Hooks

Top React Hooks — Timers, Key Presses, Local Storage

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 useInterval hook lets us run a piece of code periodically.

For instance, we can write:

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

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

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

We have the useInterval hook.

The callback is what’s run after a period.

The 2nd argument is the period.

The 3rd is whether we run the callback on mount or not.

We can use the useIsClient hook to check if JavaScript is loaded on the client-side or not.

For instance, we can write:

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

export default function App() {
  const isClient = useIsClient();

  return <div>{isClient && "client side rendered"}</div>;
}

We call the useIsClient hook which returns a boolean which indicates that the code is loaded from the client-side if it’s true .

The useKeyPress hook lets us add keydown and keyup listeners to any key.

For instance, we can write:

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

export default function App() {
  const hPress = useKeyPress("h");

  return <div>{hPress && "h key pressed"}</div>;
}

We use the useKeyPress hook by passing in a string with the key we want to watch form.

If the ‘h’ key is pressed, the hPress is true .

The useLocalStorage hook lets us set and store values in local storage.

For example, we can write:

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

export default function App() {
  const [name, setName] = useLocalStorage("name", "james");

  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={e => setName(e.target.value)}
      />
    </div>
  );
}

We use the useLocalStorage hook with the key and value to store.

It returns an array with the state and the function to set the state in this order.

The state will be automatically saved in local storage.

The useLockBodyScroll hook lets us local the scrolling.

It’s handy for creating things like modals.

For example, we can write:

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

function Modal({ title, children, onClose }) {
  useLockBodyScroll();

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal">
        <h2>{title}</h2>
        <p>{children}</p>
      </div>
    </div>
  );
}

export default function App() {
  const [isOpen, setIsOpen] = React.useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>open modal</button>
      {isOpen && (
        <Modal title="The title" onClose={() => setIsOpen(false)}>
          modal content
        </Modal>
      )}
    </>
  );
}

We use the useLockBodyScroll hook without any arguments in the Modal component.

Then we can use Modal in App to toggle it on and off.

Conclusion

React Recipes comes with hooks for running code periodically, locking scrolling, setting local storage, and watching key presses.

Categories
React Hooks

Top React Hooks — Swipes 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 Swipeable

React Swipeable is a library that lets us handle swipe events in our app.

For instance, we can write:

import React from "react";
import { useSwipeable, Swipeable } from "react-swipeable";

export default function App() {
  const handlers = useSwipeable({
    onSwiped: eventData => console.log("swiped")
  });
  return <div {...handlers}> swipe here </div>;
}

We use the useSwipeable hook which takes an object with some options.

onSwiped is a callback that runs when the we swipe on the elements with the handlers .

We can add options to the 2nd argument of the useSwipeable hook.

For instance, we can write:

import React from "react";
import { useSwipeable, Swipeable } from "react-swipeable";

export default function App() {
  const handlers = useSwipeable({
    onSwiped: eventData => console.log("swiped"),
    onSwipedLeft: eventData => console.log("swiped left"),
    onSwipedRight: eventData => console.log("swiped right"),
    onSwipedUp: eventData => console.log("swiped up"),
    onSwipedDown: eventData => console.log("swiped down"),
    onSwiping: eventData => console.log("swiping")
  });
  return <div {...handlers}> swipe here </div>;
}

to add more handlers that handlers different kinds of swiping.

React Tracked

The React Tracked is a package that lets us manage shared states.

To install it, we run:

npm install react-tracked

Then we can use it by writing:

import React from "react";
import { createContainer } from "react-tracked";

const useValue = ({ reducer, initialState }) =>
  React.useReducer(reducer, initialState);
const { Provider, useTracked } = createContainer(useValue);

const initialState = {
  count: 0
};

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { ...state, count: state.count + 1 };
    case "decrement":
      return { ...state, count: state.count - 1 };
    default:
      throw new Error(`unknown action type: ${action.type}`);
  }
};

const Counter = () => {
  const [state, dispatch] = useTracked();
  return (
    <div>
      <div>
        <span>Count: {state.count}</span>
        <button type="button" onClick={() => dispatch({ type: "increment" })}>
          increment
        </button>
        <button type="button" onClick={() => dispatch({ type: "decrement" })}>
          decrement
        </button>
      </div>
    </div>
  );
};

export default function App() {
  return (
    <>
      <Provider reducer={reducer} initialState={initialState}>
        <Counter />
        <Counter />
      </Provider>
    </>
  );
}

We create the useValue function which takes the reducer and initial state and pass them to the useReducer hook.

Then we call createContainer get the value.

The reducer is like another reducer we see.

The Counter component gets and sets the state with the useTracked hook.

state has the states we have.

dispatch is a function to dispatch our actions.

Then in App , we use the Provider returns from createContainer to let us share states with the provider.

The state is accessible with anything inside.

reducer has the reducer we created earlier.

initialState has the initial state.

And we put the Counter inside it to let us get and set the shared state.

Conclusion

React Swipeable lets us watch for swipe events and handle them.

React Tracked lets us created shared states like other popular state management solutions.

Categories
React Hooks

Top React Hooks — State and Color

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

The useActive lets us watch if an element is active.

The useInterval hook lets us run code periodically in our React component.

To use it, we can write:

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

export default function App() {
  const [time, setTime] = React.useState(null);
  const { start, stop } = useInterval({
    duration: 1000,
    startImmediate: false,
    callback: () => {
      setTime(new Date().toLocaleTimeString());
    }
  });

  return (
    <>
      <div>{time}</div>
      <button onClick={() => stop()}>Stop</button>
      <button onClick={() => start()}>Start</button>
    </>
  );
}

We use the useInterval hook in our app.

It takes an object with various properties.

duration is the duration of each period.

startImmediate means that the callback runs when the component loads if it’s true .

callback is the callback to run.

It returns an array with the stop and start functions to stop and start the timer respectively.

We then used that in our onClick handlers.

The useMap hook lets us manipulate key-value pairs in our component.

For instance, we can write:

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

export default function App() {
  const {
    set: setKey,
    get: getKey,
    has,
    delete: deleteKey,
    clear,
    reset,
    values
  } = useMap({ name: "james", age: 20 });

  return (
    <>
      <button onClick={() => setKey("foo", "bar")}>set key</button>
      <button onClick={() => deleteKey()}>delete</button>
      <button onClick={() => clear()}>clear</button>
      <button onClick={() => reset()}>reset</button>
      <div>{JSON.stringify(values)}</div>
    </>
  );
}

We used the useMap hook with an object passed in as the initial value.

It returns an object with methods or adding, getting, and removing data.

clear and reset clear the data.

deleteKey delete the data.

setKey sets the key-value pair.

React Recipes

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

To install it, we run:

npm i react-recipes --save

or:

yarn add react-recipes

Then we can use it by writing:

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

export default function App() {
  const lightGray = useAdjustColor(0.8, "#000");
  const darkerWhite = useAdjustColor(-0.4, "#fff");
  const blend = useAdjustColor(-0.2, "rgb(20,50,200)", "rgb(300,70,20)");
  const linerBlend = useAdjustColor(
    -0.5,
    "rgb(20,60,200)",
    "rgb(200,60,20)",
    true
  );

  return (
    <div>
      <div style={{ background: lightGray, height: "50px", width: "50px" }} />
      <div style={{ background: darkerWhite, height: "50px", width: "50px" }} />
      <div style={{ background: blend, height: "50px", width: "50px" }} />
      <div style={{ background: linerBlend, height: "50px", width: "50px" }} />
    </div>
  );
}

We use the useAdjustColor hook to adjust the color our way.

The first argument is the percentage between -1 and 1.

Positive is lighter and negative is darker.

The 2nd and 3rd arguments are the color code strings.

It can be hex or RGB value.

The 3rd argument is optional.

The 4th argument is the library blend, which can be hex or RGB value.

The default is false .

It returns the color string that’s created after adjusting the color.

It comes with many more hooks we can use.

Conclusion

The react-powerhooks package comes with various state management hooks.

React Recipes has color adjustment and many other kinds of hooks.