React provides the custom Hooks feature, which allows us to create a lot of interesting features. Today we share 15 Hooks that I think are cool.
If you are not already familiar with React Hooks, read this article: React Hooks
useClippy
UseClippy is a custom Hook for reading or writing to stickboards with TypeScript support.
Official documentation: github.com/CharlesStov…
Code examples:
import useClippy from 'use-clippy';
export default() = > {const [clipboard, setClipboard] = useClippy();
return (
<div>
<button
onClick={()= >{alert(' clipboard: ${clipboard} '); }} > Read the stickboard</button>
<button
onClick={()= >{setClipboard(' new content: ${math.random ()} '); }} > Writes to the stickboard</button>
</div>
);
};
Copy the code
useWindowSize
UseWindowSize Is used to obtain the size of the browser window. The default value is debounce or throttled.
Official documentation: github.com/jaredLunde/…
Code examples:
import { useWindowSize } from '@react-hook/window-size';
// import { useWindowSize } from '@react-hook/window-size/throttled';
export default (props) => {
const [width, height] = useWindowSize();
return (
<div>
width: {width}, height: {height}
</div>
);
};
Copy the code
useMediaQuery
UseMediaQuery controls the component by using CSS3 MediaQuery in the component.
Official documentation: github.com/jaredLunde/…
Code examples:
import React from 'react';
import { useMediaQuery, useMediaQueries } from '@react-hook/media-query';
// Using a single media query
// export default () => {
// const matches = useMediaQuery('only screen and (min-width: 400px)');
// return `Matches? ${matches ? 'Matched! ' : 'Nope'}`;
// };
// Using multiple media queries
export default() = > {const { matches, matchesAny, matchesAll } = useMediaQueries({
screen: 'screen'.width: '(min-width: 400px)'});return (
<ul>
<li>Screen matched? {matches.screen ? 'Yes' : 'No'}</li>
<li>Width matched? {matches.width ? 'Yes' : 'No'}</li>
<li>All matched? {matchesAll ? 'Yes' : 'No'}</li>
<li>Any matched? {matchesAny ? 'Yes' : 'No'}</li>
</ul>
);
};
Copy the code
useAsync
UseAsync is used to gracefully resolve, cancel, and handle asynchronous functions or promises, and to automatically clear them when the component is unloaded.
Official documentation: github.com/jaredLunde/…
Code examples:
import { useAsync } from '@react-hook/async';
export default() = > {const [{ status, cancel, error, value }, call] = useAsync((a)= > {
return new Promise((resolve) = > setTimeout((a)= > resolve('Loaded'), 3000));
});
switch (status) {
case 'loading':
return (
<div>
<button onClick={cancel}>Cancel</button>
Loading...
</div>
);
case 'cancelled':
return (
<div>
Cancelled.
<button onClick={call}>Try again</button>
</div>
);
case 'error':
return `Error: ${error}`;
case 'success':
return value || 'Success! ';
default:
return <button onClick={call}>Load me</button>; }};Copy the code
useBrowserContextCommunication
UseBrowserContextCommunication use Broadcast Channel API for different browser context (TAB, iframe, window) communication between provide simple solutions.
Official documentation: github.com/AvraamMavri…
Code examples:
import useBrowserContextCommunication from 'react-window-communication-hook';
export default() = > {// communicationState is a {lastMessage, messages} object used to receive data from other browser contexts
const [communicationState, postMessage] = useBrowserContextCommunication(
'channel'
);
const [status, setStatus] = useState('login');
function logout() {
setStatus('logout');
postMessage('logout');
}
const isLogout = [communicationState.lastMessage, status].includes('logout');
return (
<div>
<h1>Status: {isLogout? 'Logged out' : 'logged in '}</h1>
<button onClick={logout}>exit</button>
</div>
);
};
Copy the code
You can open two tabs in your browser and click the “Exit” button on one page to see that the pages of both tabs have changed.
useScript
UseScript is used to load external scripts dynamically and provides an onLoad callback to get the time when the script has finished loading.
Official documentation: github.com/hupe1980/re…
Code examples:
import { StripeProvider } from 'react-stripe-elements';
import useScript from 'react-script-hook';
export default() = > {const [loading, error] = useScript({ src: 'https://js.stripe.com/v3/' });
if (loading) return <h3>Loading Stripe API...</h3>;
if (error) return <h3>Failed to load Stripe API: {error.message}</h3>;
return (
<StripeProvider apiKey="pk_test_6pRNASCoBOKtIshFeQd4XMUh">
<div>Hello</div>
</StripeProvider>
);
};
Copy the code
It can also be used as a callback function:
useScript({
src: 'https://js.stripe.com/v3/'.onload: (a)= > console.log('Script loaded! ')})Copy the code
useLocalStorage
UseLocalStorage Used to access data through the localStorage API.
Official documentation: github.com/rehooks/loc…
Code examples:
import { useLocalStorage, writeStorage } from '@rehooks/local-storage';
let counter = 0;
export default() = > {const [counterData] = useLocalStorage('counter');
return (
<>
{counter}
<button onClick={()= > writeStorage('counter', ++counter)}>Write</button>
<button onClick={()= > alert(counterData)}>Read</button>
</>
);
};
Copy the code
useIdb
UseIdb uses the IndexedDB of the browser to store data, similar to useLocalStorage.
Official documentation: github.com/kigiri/reac…
Code examples:
import { useIdb } from 'react-use-idb';
export default() = > {const [value, setValue] = useIdb('my-key'.'foo');
return (
<div>
<div>Value: {value}</div>
<button onClick={()= > setValue('bar')}>bar</button>
<button onClick={()= > setValue('baz')}>baz</button>
</div>
);
};
Copy the code
use-mouse-action
Use-mouse-action Is used to listen for click events when the mouse (and possibly the touchpad) is pressed or up.
Official documentation: github.com/dimitrinico…
Code examples:
import useMouseAction from 'use-mouse-action';
export default() = > {const props = useMouseAction({
onAction: (a)= > console.log('You clicked or mouse downed me! '),
down: true});return (
<button type="button" {. props} >
Click me fast!
</button>
);
};
Copy the code
useDebounce
UseDebounce is used to delay the execution of setState or other callback functions.
Official documentation: github.com/jaredLunde/…
Code examples:
import {useDebounce, useDebounceCallback} from '@react-hook/debounce'
const Component = (props) = > {
// at a basic level, used just like useState
const [value, setValue] = useDebounce('initialValue')}const useMyCallback = (initialState, wait, leading) = > {
// this is the same code useDebounce() uses to debounce setState
const [state, setState] = useState(initialState)
return [state, useDebounceCallback(setState, wait, leading)]
}
Copy the code
useThrottle
UseThrottle is used to dilute the frequency with which setState or other callback functions are executed.
Official documentation: github.com/jaredLunde/…
Code examples:
import {useThrottle, useThrottleCallback} from '@react-hook/throttle'
const Component = (props) = > {
// at a basic level, used just like useState
const [value, setValue] = useThrottle('initialValue')}const useMyCallback = (initialState, fps, leading) = > {
// this is the same code useThrottle() uses to throttle setState
const [state, setState] = useState(initialState)
return [state, useThrottleCallback(setState, fps, leading)]
}
Copy the code
useOnlineStatus
The useOnlineStatus command is used to obtain the current network status by listening for online and offline events.
Official documentation: github.com/rehooks/onl…
Code examples:
import useOnlineStatus from '@rehooks/online-status';
export default() = > {const onlineStatus = useOnlineStatus();
return (
<div>
<h1>You are {onlineStatus ? 'Online' : 'Offline'}</h1>
</div>
);
};
Copy the code
useDocumentTitle
UseDocumentTitle Is used to update the page title.
Official documentation: github.com/rehooks/doc…
Code examples:
import useDocumentTitle from '@rehooks/document-title';
export default () => {
useDocumentTitle('Page Title');
return <div />;
};
Copy the code
useNetworkStatus
UseNetworkStatus exposes navigator.Connection objects for real-time access to network status.
Official documentation: github.com/rehooks/net…
Code examples:
import useNetworkStatus from '@rehooks/network-status';
export default() = > {let connection = useNetworkStatus();
return (
<div>
<div>downlink: {connection.downlink}</div>
<div>effectiveType: {connection.effectiveType}</div>
<div>rtt: {connection.rtt}</div>
<div>saveData: {connection.saveData ? 'yes' : 'no'}</div>
</div>
);
};
Copy the code
useSpeechSynthesis
UseSpeechSynthesis provides Speech recognition and text-to-speech capabilities using the Web Speech API, as well as English and Chinese language recognition.
The official document: www.npmjs.com/package/rea… Example: online mikeyparton. Making. IO/react – speec…
Code examples:
import { useSpeechSynthesis, useSpeechRecognition } from 'react-speech-kit';
export default() = > {const [value, setValue] = useState(' ');
const { speak } = useSpeechSynthesis();
const { listen, listening, stop } = useSpeechRecognition({
onResult: (result) = >{ setValue(result); }});return (
<div>
<textarea
value={value}
onChange={(event)= > setValue(event.target.value)}
/>
<br />
<button onMouseDown={listen} onMouseUp={stop}>
Listen
</button>
<button onClick={()= > speak({ text: value })}>Speak</button>
{listening && <div>Go ahead I'm listening</div>}
</div>
);
};
Copy the code
You can hold down the Listen button and say anything, and it will automatically recognize what’s in the text box, and then click the Speak button, and it will automatically recognize what’s in the text box and Speak it back.