SECRET OF CSS

12 React Hooks Every React Developer Should Know | by Trevor-Indrek Lasn | Aug, 2022


Use these hooks to save time and be more productive. Some of them are game changers

0*SCAJY j3ywJE8YNK
Photo by Rahul Mishra on Unsplash

React hooks are highly reusable parts of functionality. Hooks let us Eencapsulate side effects and compose and reuse logic.

For most use cases, there’s a react hook for it. Why reinvent the wheel when there’s such a vast amount of open source hooks we can start using today?

If you’re new or unsure about hooks — see my previous article where I demystify React Hooks.

React Swipeable is a react swipe event handler hook. React Swipeable is a must have for building mobile-first react apps in some circumstances.

1*d9VdjdLFFNtD7S9DVZvlTw
Demo

Let’s say you’re developing an e-commerce shop. You’ll want to enable “native” mobile behavior on your web application.

Mobile users interact with apps much differently than web users. Phones have touch gestures, swipes, zoom in and out, etc. Why not enable all these features for your web mobile apps?

How it works

const handlers = useSwipeable({
onSwiped: (eventData) => console.log("User Swiped", eventData),
...config,
});
return <div {...handlers}> swipe here </div>;

Here are all the props you can access when handling events.

{
onSwiped, // After any swipe (SwipeEventData) => void
onSwipedLeft, // After LEFT swipe (SwipeEventData) => void
onSwipedRight, // After RIGHT swipe (SwipeEventData) => void
onSwipedUp, // After UP swipe (SwipeEventData) => void
onSwipedDown, // After DOWN swipe (SwipeEventData) => void
onSwipeStart, // Start of swipe (SwipeEventData) => void *see details*
onSwiping, // During swiping (SwipeEventData) => void
onTap, // After a tap ({ event }) => void
// Pass through callbacks, event provided: ({ event }) => void
onTouchStartOrOnMouseDown, // Called for `touchstart` and `mousedown`
onTouchEndOrOnMouseUp, // Called for `touchend` and `mouseup`
}

See the react-swipeable NPM page for information about integration and usage.

use-resize-observer is a React hook that allows you to measure an element’s width and height.

CodeSandbox Demo

This hook comes incredibly handy when working with image cropping, editing, processing, etc.

How to use

See the NPM page for further instructions.

When it comes to forms — Formik handles the repetitive and tedious parts.

It keeps track of values, errors, visited fields, orchestrating validation, and handling submission — stuff you don’t have to deal with anymore. Spend less time wiring up state and change handlers.

How it works

Imagine we want to add a newsletter signup form for a blog. To start, our form will have just one field named email. With Formik, this is just a few lines of code.

Example source.

See the Formik documentation page for information about integration and usage.

Debouncing in JavaScript is a pattern used to improve browser performance.

There might be some functionality in a web page that requires time-consuming computations. Like image uploading, multiple API calls, etc.

If such methods are invoked too frequently, it will greatly affect the browser’s performance.

Debouncing is a programming practice that ensures time-consuming tasks do not fire so often.

How it works

See the use-debounce NPM page for further information.

React has a bunch of hooks out of the box. One of them is useLayoutEffect

The React documentation says about useLayoutEffect:

useLayoutEffect signature is identical to the useEffecthook — but fires synchronously after all DOM mutations.

That means you can use the useLayoutEffecthook browser-only. This is a problem if you’re rendering your react code server-side. For example, using NextJS, you’ll get this error message:

Warning: useLayoutEffect does nothing on the server because its effect cannot be encoded into the server renderer’s output format.

To avoid this error message — useLayoutEffect should only be used in components that render exclusively on the client.

The useIsomorphicLayoutEffect fixes the problem by switching between useEffect and useLayoutEffect following the execution environment.

How to use

+ import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';- import { useLayoutEffect } from 'react';const YourComponent = () => {+  useIsomorphicLayoutEffect(() => {
// your implementation
}, []);
- useLayoutEffect(() => {
// your implementation
}, []);
};

See the NPM package page for more information.

SWR is a React Hooks library for data fetching. The name “SWR” is derived from stale-while-revalidate

stale-while-revalidateis a cache invalidation strategy popularized by HTTP RFC 5861.

How to use

import useSWR from 'swr'function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>}

SWR first returns the data from cache (stale), sends the request (revalidate), and finally comes with the up-to-date data again.

Significantly simplify the data fetching logic in your project. And it also covered all aspects of speed, correctness, and stability to help you build better apps.

With SWR, all components will get a stream of data updates constantly and automatically. The UI will be fast and reactive.

View full documentation and examples on swr.vercel.app.

react-hotkeys-hook is for using keyboard shortcuts in components. The hook allows to listen to hotkeys in a declarative way and execute a callback function once the user pressed down the given hotkey.

How it works

import { useHotkeys } from 'react-hotkeys-hook';function ExampleComponent() {
useHotkeys('a', () => alert('Key a was pressed'))
return (
<span>Press the a key to see it work.</span>
)

react-hotkeys-hook also listen to keystrokes. A keystroke is a combination of keys the user must hit to execute the callback. Let’s imagine our app has shortcuts for functionality. Such as creating a Jira ticket by pressing shift+c.

See the official documentation for further examples

@use-gesture is a library that lets you bind richer mouse and touch events to any component or view. It’s simple to set up gestures with the props you get.

1*7PqZiJS26d 9l0VrMbJddA
1*rRVmUR636muT3yppKkX4YA

Some apps require gestures by default and are expected. For example, gestures are a must-have if you’re building a Kanban board-like app.

@use-gesture/react exports several hooks that can handle different gestures. Be sure to check them all out for an in-depth dive.

1*jTL6tJ 24WRQELeAHGb9pQ
More on the full documentation website

P.S. You can use it stand-alone, but to make the most of it, you should combine it with an animation library like react-spring. Though you can most certainly use any other.

react-script-hook is a hook to dynamically load an external script and know when it’s loaded. Great when working with third-party APIs, such as Stripe, Twilio, etc.

Imagine you’re using the Stripe API for accepting payments. We don’t want to break our app by letting users interact with payments when the API hasn’t been fully loaded yet. This hook solves the before-mentioned problem.

How to use

The hook automatically handles when the script was already loaded (or started loading) from another hook instance.

You can safely add identical useScript hooks to multiple components that depend on the same external script, and they will properly block the loading of only one copy.

See the NPM package documentation for further instructions.

react-scroll-parallax is a hook that lets you easily have parallax scroll effects for banners, images, or any other DOM elements.

1*CnXQTr00x 5s3 DTObfBLg
Demo source: https://react-scroll-parallax-v3.surge.sh/?path=/story/components-parallax-rotate-props–with-rotation

Parallax scrolling offers the ideal setting to tell your story engagingly and interactively. Let your visitors take control and walk through your story at their own pace. source

How to use

As the element scrolls past the viewport, a CSS translate effect is applied based on the original element’s position relative to the viewport.

import { useParallax } from 'react-scroll-parallax';function Component() {
const parallax = useParallax({
speed: -10,
});
return <div ref={parallax.ref} />;
}

Using the speed will automatically apply a translateY CSS style (or translated if the scroll axis is horizontal).

You can spin an element around its axis using the rotate props. Use the rotate prop to rotate an element around the z-axis.

const Component = () => {
const parallax = useParallax<HTMLDivElement>({
rotate: [0, 360],
});
return (
<div ref={parallax.ref} className="spinner">
😵‍💫
<div className="diamond">💎</div>
<div className="clown">🤡</div>
<div className="money">💰</div>
<div className="hand">👌🏻</div>
</div>
);
};
Source: https://react-scroll-parallax.damnthat.tv/docs/usage/parallax-props#available-css-effects

For an in-depth dive, please see the how it works section.

react-storage-hooks is used for keeping the application state in sync with localStorage or sessionStorage.

The useStorageState and useStorageReducer hooks included in this library work similar touseState and useReducer. There are a couple of differences, though. See the how-to section for a further in-depth dive.

How to use

@chakra-ui/color-modeis a React component + Hook that adds support for light mode and dark mode using localStorage and matchMedia.

I’m a big fan of the dark theme. This hook makes it simple for users to choose between a dark or a light theme.

How to use

Wrap your application in a ColorModeProvider below the ThemeProvider

import * as React from "react"
import { ColorModeProvider } from "@chakra-ui/color-mode"
import theme from "./theme"
function App({ children }) {
return (
<ThemeProvider theme={theme}>
<ColorModeProvider>{children}</ColorModeProvider>
</ThemeProvider>
)
}

Next, use the hook useColorMode within your application.

function Example() {
const { colorMode, toggleColorMode } = useColorMode()
return (
<header>
<Button onClick={toggleColorMode}>
Toggle {colorMode === "light" ? "Dark" : "Light"}
</Button>
</header>
)
}

See this page for further instructions.



News Credit

%d bloggers like this: