Open collection of custom react hooks. π₯
We all unfathomably love react hooks and all the glory it brings to the codebase. This repo is on a mission to collect all amazing custom hooks out there and put it in one place for everyone to access and applaud.
- Complete source code - no referencing an npm package or repo URL.
- One stop shop to draw inspiration/ideas to build your own hooks.
- You get to show off your hooks - full credit to hook author.
If you want to add your hook to this repo, create a PR with the following info.
- Fork this repo
- Add your hook source code as a
.js
file inhooks
dir. (Eg.useMeow.js
) - Add your name and twitter/github handles as comments at the end of the file.
- Add your hook name and code in
README.md
file. Refer to other hooks and follow the same approach.
Author - Dinesh Pandiyan
export default function useFormField(initialVal = '') {
const [val, setVal] = React.useState(initialVal);
const [isValid, setValid] = React.useState(true);
function onChange(e) {
setVal(e.target.value);
if (!e.target.value) {
setValid(false);
} else if (!isValid) setValid(true);
}
function setValidManually(bool = false) {
setValid(bool);
}
return [val, onChange, isValid, setValidManually];
}
Wrap async calls and get their loading status.
Author - Shawn Wang
export default function useLoading() {
const [isLoading, setState] = React.useState(false);
const load = (aPromise) => {
setState(true);
return aPromise
.then((...args) => {
setState(false);
return Promise.resolve(...args);
})
.catch((...args) => {
setState(false);
return Promise.reject(...args);
});
};
return [isLoading, load];
}
Get current width from the window
object.
Author - Alex Anderson
export default function useWindowWidth() {
const [windowWidth, setWindowWidth] = React.useState(window.innerWidth);
const resize = () => setWindowWidth(window.innerWidth);
useEffect(() => {
window.addEventListener('resize', resize);
return () => window.removeEventListener('resize', resize);
});
return windowWidth;
}
Invoke a function after a specified interval
Author - Dan Abramov
export default function useInterval(callback, delay) {
const savedCallback = React.useRef();
// Remember the latest callback.
React.useEffect(() => {
savedCallback.current = callback;
});
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
return () => {};
}, [delay]);
}
MIT license, Copyright (c) 2019 Dinesh Pandiyan.