Install with npm
npm install @kirekov/great-hooks
Or with yarn
yarn add @kirekov/great-hooks
✔️ The library has been written in TypeScript. So, it supports types checking.
How many times have you written this?
function MyComponent(props) {
const ref = useRef<string>(props.value);
useEffect(() => {
ref.current = props.value;
}, [props.value]);
...
}
Forget about it. That's all you need now.
import { useAutoUpdateRef } from '@kirekov/great-hooks';
function MyComponent(props) {
const ref = useAutoUpdateRef<string>(props.value);
...
}
If you need to invoke useEffect
only once, you can use that hook.
import { useEffectOnce } from "@kirekov/great-hooks";
function MyComponent(props) {
useEffectOnce(() => {
someHeavyOperation();
})
}
If you need to start an interval inside your component, useInterval
might be handy.
import { useInterval } from '@kirekov/great-hooks';
function EndlessTimer(props) {
...
const onUpdate = () => { ... };
useInterval({ callback: onUpdate, interval: 5000 })
}
...
interface UseIntervalParams {
callback: () => any
interval: number
delay?: number
}
delay
attribute defines the pause time before the first callback
invocation.
If you need to start the interval again, just call the restart
function.
const restart = useInterval({ callback: onUpdate, interval: 5000 })
const onRestart = () => {
restart().then(() => {
console.log('The interval has been restarted!')
})
}
Although React
provides us with convenient API to bind event listeners to the DOM,
sometimes it's required to come up with custom solutions. For example, we can do it like this.
function CustomEventComponent(props) {
...
useEffect(() => {
document.addEventListener('click', onCustomClick);
return () => {
document.removeEventListener('click', onCustomClick);
};
}, [])
}
Thankfully great-hooks
gives much simpler solution.
import { useEventListener } from '@kirekov/great-hooks';
function CustomEventComponent(props) {
...
useEventListener({ eventName: 'click', onEventTriggered: onCustomClick, eventTarget: document });
}
Have you faced with a problem when you need to execute something exactly after the new state has been saved?
It can be easily done with setState
approach.
this.setState({ greetings: 'Hi there' }, () => { ... })
So, what about hooks API? great-hooks
provides an easy way to do it.
import { useStateWithCallback } from '@kirekov/great-hooks';
function MyComponent(props) {
const [counter, setCounter] = useStateWithCallback<number>(0);
function increment() {
setCounter(prevCounter => prevCounter + 1, newCounterValue => {
console.log('newCounterValue', newCounterValue);
})
}
}
Additionally, the lib provides Promise-like api to handle state updates.
import { useStateWithPromise } from '@kirekov/great-hooks';
function MyComponent(props) {
const [counter, setCounter] = useStateWithPromise<number>(0);
function increment() {
setCounter(prevCounter => prevCounter + 1)
.then(newCounterValue => {
console.log('newCounterValue', newCounterValue);
})
}
}