Categories
React Hooks

Top React Hooks — Previous State, Online Status and Scripts

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 useMedia hook lets us add media queries in JavaScript.

For instance, we can write:

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

export default function App() {
  const columnCount = useMedia(
    ["(min-width: 1500px)", "(min-width: 1000px)", "(min-width: 600px)"],
    [5, 4, 3],
    2
  );

  return (
    <div style={{ columns: columnCount }}>
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We have the useMedia hook to set the media query.

The first argument is an array of media queries.

The 2nd is the array of values for each media query.

The 3rd is the default value to return.

Then we can use the returned value as we wish.

In the example above, we used the media queries to set the number of columns.

The useOnClickOutside hook lets us listen for clicks outside an element.

For instance, we can write:

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

export default function App() {
  const ref = React.useRef();
  const [isModalOpen, setModalOpen] = React.useState(false);

  useOnClickOutside(ref, () => setModalOpen(false));

  return (
    <div>
      {isModalOpen ? (
        <div ref={ref}>modal</div>
      ) : (
        <button onClick={() => setModalOpen(true)}>Open Modal</button>
      )}
    </div>
  );
}

We used the useOnClickOutside hook with a ref.

The ref is passed to the element that we want to watch for clicks outside.

The hook takes a callback to run some code when we click outside an element.

The useOnlineStatus hook lets us listen for the online or offline events to see the current status.

For instance, we can use it by writing:

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

export default function App() {
  const onlineStatus = useOnlineStatus();

  return (
    <div>
      <h1>{onlineStatus ? "Online" : "Offline"}</h1>
    </div>
  );
}

We called the useOnlineStatus hook to listen to the online status.

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

For example, we can write:

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

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

  const prevCount = usePrevious(count);

  return (
    <div>
      <p>
        Now: {count}, before: {prevCount}
      </p>
      <button onClick={() => setCount(count => count + 1)}>Increment</button>
    </div>
  );
}

We use the usePrevious hook with the count state to return the count state’s previous value.

prevCount has the previous value of count .

The useScript hook lets us create a scrip tag with our code.

For instance, we can write:

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

export default function App() {
  const [loaded, error] = useScript(
    "https://code.jquery.com/jquery-2.2.4.min.js"
  );

  return (
    <div>
      <div>
        Script loaded: <b>{loaded.toString()}</b>
      </div>
      {loaded && !error && (
        <div>
          Script function call response: <b>{$().jquery}</b>
        </div>
      )}
    </div>
  );
}

We called the useScript hook with the URL for our script.

We loaded jQuery and get the jQuery version with $().jquery .

loaded indicates that it’s loaded if it’s true ,

error has the error if there’s one.

Conclusion

React Recipes lets us use media queries, load scripts, watch online status, and get the previous value of a state.

Categories
React Hooks

Top React Hooks — Portal and Flux

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 Portal

React Cool Portal lets us render our elements outside the usual DOM hierarchy determined by React.

To install it, we run:

yarn add react-cool-portal

or:

npm install --save react-cool-portal

Then we can use it by writing:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal } = usePortal();

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

We called the usePortal hook to return the Portal component.

Then we can render our elements inside the Portal .

By default, the elements inside will be attached to the body.

We can add the ID of the container with the containerId .

If the element with the given ID doesn’t exist, it’ll create it for us.

For instance, we can write:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal } = usePortal({ containerId: "portal" });

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

It also comes with states that we can use to determine whether we show or hide the element in the portal.

For example, we can write:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal, isShow, show, hide, toggle } = usePortal({
    defaultShow: false,
    onShow: e => {
      // ...
    },
    onHide: e => {
      // ...
    }
  });

  return (
    <div>
      <button onClick={show}>Open</button>
      <button onClick={hide}>Close</button>
      <button onClick={toggle}>{isShow ? "Close" : "Open"} Modal</button>
      <Portal>
        <div class="modal" tabIndex={-1}>
          <div>
            <h5>Modal title</h5>
            <p>Modal body.</p>
          </div>
        </div>
      </Portal>
    </div>
  );
}

We used the userPotal hook to get more properties from the returned object.

It returns the show and hide functions to show and hide the portal.

toggle is a function to toggle the portal.

isShow has the state to indicate whether the portal is shown or not.

defaultShow sets whether the portal elements are shown by default or not.

onShow is the function to run something when the portal is shown.

onHide is the function that runs when the portal is hidden.

react-enhanced-reducer-hook

The react-enhanced-reducer-hook library lets us create a centralized data store in our app.

It’s inspired by Redux and works similarly to it.

To install it, we run:

npm install react-enhanced-reducer-hook --save

Then we can use it by writing:

import React from "react";
import useEnhancedReducer from "react-enhanced-reducer-hook";

function logMiddleware({ getState }) {
  return next => action => {
    console.log("Prev State:", getState());
    console.log("Action:", action);
    next(action);
    console.log("Next State:", getState());
  };
}

function useAppReducer(reducer, inititalState) {
  return useEnhancedReducer(reducer, inititalState, [logMiddleware]);
}

function counterReducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: 0 };
    default:
      return state;
  }
}

export default function App() {
  const [state, dispatch] = useAppReducer(counterReducer, { count: 0 });
  return (
    <React.Fragment>
      <button onClick={() => dispatch({ type: "increment" })}>increment</button>
      <button onClick={() => dispatch({ type: "decrement" })}>decrement</button>
      <button onClick={() => dispatch({ type: "reset" })}>reset</button>
      <br />
      Count: {state.count}
    </React.Fragment>
  );
}

We have the useAppReducer hook, which we pass the counterReducer into it.

The hook is created by us by using the useEnhancedReducer hook where we pass the reducer, initial state, and any middleware that we want to run into it.

We return the results of useEnhancedReducer so that we can use it in our component.

The Redux reducer is like any other reducer.

We have the logMiddleware that we can run during state changes.

In App , we get the state and dispatch variables.

state has the current state.

And dispatch has the function to dispatch our actions.

The type is the action type.

Then we get the count state with state.count .

Conclusion

React Cool Portal lets us create portals without the hassle.

The react-enhanced-reducer-hook library lets us create a centralized data store.

The library is inspired by Redux.

Categories
React Hooks

Top React Hooks — Placeholder and Titles

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-optimistic-ui-hook

The react-optimistic-ui-hook library lets us create a UI that doesn’t wait for an operation to finish to update the final state.

They immediately switch to the final state and show fake data while the read ones are loading.

We can install it by running:

npm install react-optimistic-ui-hook

or:

yarn add react-optimistic-ui-hook

Then we can use it by writing:

import React from "react";
import { useOptimisticUI } from "react-optimistic-ui-hook";

const USERNAME = "facebook";
const PREDICTED_AVATAR_URL = "http://placekitten.com/200/200";
const DELAY_IN_MS = 2000;

async function getGithubAvatarURL(username) {
  const response = await fetch(`https://api.github.com/users/${username}`);
  const data = await response.json();

  return new Promise(resolve => {
    setTimeout(() => {
      resolve(data.avatar_url);
    }, DELAY_IN_MS);
  });
}

export default function App() {
  const { status, result, error } = useOptimisticUI(
    () => getGithubAvatarURL(USERNAME),
    PREDICTED_AVATAR_URL
  );

  return (
    <div>
      <img src={result} alt="avatar" />
      <p>Status: {status}</p>
      <p>Error: {JSON.stringify(error)}</p>
    </div>
  );
}

We have the getGithubAvatarURL function that gets the avatar of the Github user asynchronously.

Then we can use that with the useOptimisticUI hook to run the promise.

The first argument has the callback that gets the data.

The 2nd is the URL for the placeholder to show when the real data is being downloaded.

The hook returns the status which is the loading status of the image.

result is the result, which is the resolved value of the promise returned from getGithubAvatarURL .

error has any errors that occurred.

React Page Name

React Page Name is a library that lets us update the page title in our React app.

To install it, we run:

npm install react-page-name

Then we can use it by writing:

import React from "react";
import { usePageName } from "react-page-name";

export default function App() {
  usePageName("hello world");

  return <div>hello world</div>;
}

The usePageName hook takes the string with the page title as an argument.

It also comes with a higher-order component.

For instance, we can write:

import React from "react";
import { withPageName } from "react-page-name";

let Page = () => {
  return <div>hello world</div>;
};

Page = withPageName("hello world")(Page);

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

We created the Page component and used the withPageName higher-order component to set the page title.

The higher-order component will also make the setPageName method available to our component, so we can write:

import React from "react";
import { withPageName } from "react-page-name";

let Page = ({ setPageName }) => {
  setPageName("hello world");

  return <div>hello world</div>;
};

Page = withPageName()(Page);

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

Conclusion

react-optimistic-ui-hook lets us show a placeholder until the real data is loaded.

React Page Name lets us change the page title with a hook or higher-order component.

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.