This is my frequently used react hooks, which I'll install in almost every project I create or work on. So that I don't have to keep copy pasting the files in each project.
Most of them are inspired by WDS on youtube
To install
yarn add @curiosbasant/react-compooks
OR
npm install @curiosbasant/react-compooks
These hooks can work on all react applications
function ExampleComponent() {
const info = useDebugInfo("example-component")
return (
)
}
Same as react's useEffect
, but only run once the component mounts. It doesn't requires any dependencies.
function ExampleComponent() {
const [loading, toggleLoading] = useToggle(true)
useEffectOnce(() => {
toggleLoading()
})
return // JSX
}
const ActionMap = {
increment(draft, by = 1, allowNegative = false) {
if (allowNegative || by > 0) {
draft.count += by
}
},
decrement(draft, by = 1) {
draft.count -= by
},
}
const initialState = {
count: 0,
}
function ExampleComponent() {
const [state, dispatch] = useFunctionalReducer(ActionMap, initialState)
return (
<div>
<button onClick={() => dispatch.decrement()}>Decrement</button>
<button onClick={() => dispatch.increment(-5, true)}>Increment</button>
</div>
)
}
Tracks the number of times, the component has been rerendered since last reset.
function ExampleComponent() {
const [count, reset] = useRenderCount()
return (
<div>
<span>Render Count: {count}</span>
<button onClick={() => reset()}>Reset Count</button>
</div>
)
}
Provides a bool value (default false) that can be toggled.
function ExampleComponent() {
const [bool, toggleBool] = useToggle()
return (
<div>
<span>Bool Value: {bool}</span>
<button onClick={() => toggleBool()}>Toggle Bool</button>
</div>
)
}
Validates a state before updating it.
function ExampleComponent() {
const [value, setValue, isValid] = useValidatorState(5, (val) => val < 10)
return // JSX
}
These hooks only works in browsers
Tries to get a value from browser's localstorage
, if it doesn't exist returns the optionally provided default value, otherwise returns null
.
The third return value, completely removes the key from localstrorage
function ExampleComponent() {
const [userId, setUserId, removeUserId] = useLocalStorage("userId", "default-id")
return // JSX
}
Listens to browser's dom events, on the optinally provided element-ref
or window
otherwise.
function ExampleComponent() {
const divRef = useRef()
useEventListener("mouseover", () => {}, divRef)
return <div ref={divRef}>Hover me!</div>
}
Uses the setTimeout
function, to run the callback after a certain amount of time. Also returns two methods viz. reset
(to reset the time) and clear
(to cancel)
function ExampleComponent() {
const { reset, clear } = useTimeout(() => {}, 1000)
return // JSX
}
Uses the useEventListener
hook, to detect if user has internet connectivity.
function ExampleComponent() {
const isOnline = useOnlineStatus()
return // JSX
}