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.

Categories
React Hooks

Top React Hooks — Lifecycle and Toggles

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

Then we can use the useDidUpdate hook.

This is similar to the componentDidUpdate method in React class components.

It runs only on updates.

For example, we can use it by writing:

import React from "react";
import { useDidUpdate, useCounter } from "react-hooks-lib";

export default function App() {
  const { count, inc } = useCounter(0);
  useDidUpdate(() => {
    console.log("update");
  });
  return (
    <div>
      {`count: ${count}`}
      <button onClick={() => inc(1)}>increment</button>
    </div>
  );
}

We use the useCounter hook to create a counter state.

We use the inc function to increment it.

And count has the state.

useDidUpdate ‘s callback runs when count updates.

The useMergeState hook lets us create a state setter function that works like the setState method of React class components.

For instance, we can use it by writing:

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

export default function App() {
  const { state, set } = useMergeState({ name: "james", age: 1 });

  return (
    <div>
      <button onClick={() => set(({ age }) => ({ age: age + 1 }))}>
        increment age
      </button>
      {JSON.stringify(state)}
    </div>
  );
}

useMergeState takes the initial state as the argument.

It returns the state with the state’s value.

set lets us set the stare by passing in an object.

The object will be merged with the existing state value.

We pass a function into it which has the current state object as the parameter, and we return the new state object as the value.

The useCounter hook lets us create a number state that we can update.

For instance, we can write:

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

export default function App() {
  const { count, inc, dec, reset } = useCounter(1);

  return (
    <div>
      {count}
      <button onClick={() => inc(1)}>increment</button>
      <button onClick={() => dec(1)}>decrement</button>
      <button onClick={reset}>reset</button>
    </div>
  );
}

to create a component with a number state count with the useCounter hook.

The argument is the initial value of count .

inc increments count .

dec increments count .

reset resets count to the initial value.

The useToggle hook creates a boolean state and lets us toggle it between true or false .

To use it, we write:

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

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

  return (
    <div>
      <button onClick={toggle}>toggle</button>
      <button onClick={reset}>reset</button>
      <p>{String(on)}</p>
    </div>
  );
}

We use the useToggle hook with initial value as the argument.

The on property has the toggle state’s value.

toggle lets us toggle the value of on .

And reset resets on to the initial value.

Conclusion

React Hooks Lib comes with hooks that imitates lifecycle methods of class components.

It also comes with hooks to let us manipulate various kinds of states more easily.

Categories
React Hooks

Top React Hooks — Lifecycle and 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

Then we can use the useBoolean hook to let us toggle a boolean value.

For instance, we can write:

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

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

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

We use the useBoolean hook with the initial value.

It returns an object with the toggle and the value properties.

toggle lets us toggle the boolean value.

value has the current value.

The returned object also has the setTrue and setFalse methods to set the boolean state to true and false respectively.

The useOnMount hook lets us run code when the component is mounting.

For example, we can write:

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

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

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

Whatever we have in the useOnMount callback is run.

Likewise, we have the useOnUnmount hook to run code when the component unmounts.

For instance, we can write:

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

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

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

And the callback will run when the component unmounts.

The useLifecycleHooks hook lets us add lifecycle hooks as we did with React class components.

For example, we can write:

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

export default function App() {
  useLifecycleHooks({
    onMount: () => console.log("mounted"),
    onUnmount: () => console.log("unmounting")
  });

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

We passed an object into the useLifecycleHooks hook to run code when we mount or unmount our component.

onMount is run when the component mounts.

onUnmount is run when the component unmounts.

The useCounter hook lets us create a number state and manage it.

We can use it with one argument which sets the initial state:

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

export default function App() {
  const { increase, decrease, value } = useCounter(0);

  return (
    <div>
      <button onClick={() => increase()}>increase</button>
      <button onClick={() => decrease()}>decrease</button>
      <p>{value}</p>
    </div>
  );
}

The useCounter hook takes an argument which is the initial value.

It returns an object with various properties.

increase increases the value by 1.

decrease decreases the value by 1.

value has the value.

Also, we can set the upper and lower limit of the value .

This way, those functions can’s change our value beyond the range.

For example, we can write:

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

export default function App() {
  const { increase, decrease, value } = useCounter(1, {
    upperLimit: 5,
    lowerLimit: 0
  });

  return (
    <div>
      <button onClick={() => increase()}>increase</button>
      <button onClick={() => decrease()}>decrease</button>
      <p>{value}</p>
    </div>
  );
}

We can also add the loop property so that the value loops when we change the value beyond the range:

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

export default function App() {
  const { increase, decrease, value } = useCounter(1, {
    upperLimit: 5,
    lowerLimit: 0,
    loop: true
  });

  return (
    <div>
      <button onClick={() => increase()}>increase</button>
      <button onClick={() => decrease()}>decrease</button>
      <p>{value}</p>
    </div>
  );
}

Conclusion

React hookedUp has various hooks to let us manage various kinds of states and provide us with lifecycle hooks.

Categories
React Hooks

Top React Hooks — Input, Modals, and Lazy Load Images

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

The react-use-input lets us bind to inputs easily with our React component.

To use it, we run:

yarn add react-use-input

Then we can use it by writing:

import React from "react";
import useInput from "react-use-input";

export default function App() {
  const [name, setName] = useInput();

  return (
    <>
      <input value={name} onChange={setName} />
      <p>{name}</p>
    </>
  );
}

We just use the useInput hook, which returns an array with the form field state and the function to set the input value to the form field state.

Likewise, we can do the same for a checkbox.

For example, we can write:

import React from "react";
import useInput from "react-use-input";

export default function App() {
  const [selected, setSelected] = useInput(false, "checked");

  return (
    <>
      <input type="checkbox" checked={selected} onChange={setSelected} />
      <p>{selected.toString()}</p>
    </>
  );
}

The useInput hook takes 2 arguments.

The first is the checked value.

The 2nd is the attribute name.

We can pass the state and the state setter function into our checkbox input.

react-use-lazy-load-image

react-use-lazy-load-image lets us lazy load our images.

This means that the image loads only when we display the image.

To install it, we run:

npm i react-use-lazy-load-image

Then we can use it by writing:

import React from "react";
import useLazyLoadImage from "react-use-lazy-load-image";

export default function App() {
  useLazyLoadImage();

  return (
    <>
      <img
        src="https://placekitten.com/g/200/200"
        data-img-src="https://placekitten.com/g/600/600"
        alt="cat"
      />
    </>
  );
}

src has the URL of the placeholder image.

data-img-src has the lazy-loaded image.

useLazyLoadImage lets us do the lazy loading.

react-use-modal

The react-use-modal library lets us create a toggle to toggle our modal.

To install it, we run:

yarn add react-use-modal

or:

npm install react-use-modal --save

Then we can use it by writing:

index.js

import React from "react";
import ReactDOM from "react-dom";
import { ModalProvider } from "react-use-modal";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ModalProvider>
    <App />
  </ModalProvider>,
  rootElement
);

App.js

import React from "react";
import { Modal } from "react-bootstrap";
import { useModal } from "react-use-modal";

export default function App() {
  const { showModal, closeModal } = useModal();

  function handleClick() {
    showModal(({ show }) => (
      <Modal show={show} onHide={closeModal}>
        <Modal.Header closeButton>
          <Modal.Title>Modal title</Modal.Title>
        </Modal.Header>
        <Modal.Body>Modal body.</Modal.Body>
      </Modal>
    ));
  }

  return <button onClick={handleClick}>modal</button>;
}

We use the ModalProvider and wrap that in our app.

Then we can use the useModal in App to get an object with the showModal and closeModal functions.

showModal is used to render the modal.

We pass a function with the modal content.

closeModal lets us close the modal.

We use React Bootstrap to make creating the modal easier.

Conclusion

react-use-input lets us create inputs easily.

react-use-lazy-load-image lets us lazy load images.

react-use-modal is useful for letting us toggle modals.

Categories
React Hooks

Top React Hooks — IDs, Infinite Scrolling, and IndexDB

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

The react-use-id-hook library lets us create unique IDs easily within our React component.

We can install it by running:

npm i react-use-id-hook

Then we can use it by writing:

index.js

import React from "react";
import ReactDOM from "react-dom";
import { IdProvider } from "react-use-id-hook";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <IdProvider>
    <App />
  </IdProvider>,
  rootElement
);

App.js

import React from "react";
import { useId } from "react-use-id-hook";

export default function App() {
  const id = useId();
  const [value, setValue] = React.useState();

  return (
    <form>
      <input
        id={id}
        type="checkbox"
        checked={value}
        onChange={ev => setValue(ev.target.checked)}
      />
      <label htmlFor={id}>Click me</label>
    </form>
  );
}

We use the useId hook to generate our ID.

Then we pass it into props or wherever we want to use it.

We’ve to remember to wrap our app with the IdProvider so we can use the hook.

react-use-idb

react-use-idb lets us use IndexDB to store our data without using the native library.

To install it, we run:

npm i react-use-idb

Then we can use it by writing:

import React from "react";
import { useIdb } from "react-use-idb";

export default function App() {
  const [value, setValue] = useIdb("key", "foo");

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

The useIdb hook takes a key and initial value.

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

Then we can use that as we did in the onClick handlers.

It takes one argument to set the data.

react-use-infinite-loader

The react-use-infinite-loader package lets us add infinite scrolling to our React app.

To install it, we run:

yarn add react-use-infinite-loader

Then we can use it by writing:

import React from "react";
import useInfiniteLoader from "react-use-infinite-loader";

export default function App() {
  const [canLoadMore, setCanLoadMore] = React.useState(true);
  const [data, setData] = React.useState([]);
  const loadMore = React.useCallback(() => {
    setTimeout(() => {
      setCanLoadMore(true);
      setData(currentData => [
        ...currentData,
        ...Array(20)
          .fill()
          .map((_, i) => i)
      ]);
    }, 1000);
  });
  const { loaderRef } = useInfiniteLoader({ loadMore, canLoadMore });

  return (
    <>
      {data.map(data => (
        <div>{data}</div>
      ))}
      <div ref={loaderRef} />
    </>
  );
}

We added the loadMore function to load our data,.

We put our data loading code in a callback so that the calls can be cached.

The data loading code just push more data into the data array.

Then we have the useInfiniteLoader to let us create a ref for the element to watch the for items to load.

The hook takes an object with the loadMore function to load more data.

canLoadMore tells the library whether we have more data to load.

We pass it into the div so that new data will load when we load the div.

Conclusion

The react-use-id-hook lets us create an ID in our React component.

react-use-idb is a library that lets us interact with the browser’s indexedDB database.

The react-use-infinite-loader library lets us add infinite scrolling to our React app.