@grantpearceuk/hooks
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

Custom React Hooks

View hooks in action (Examples)

useToggle

Easily toggle between a boolean

const [value, toggleValue] = useToggle(false)

<Button onClick={() => toggleValue()}>
    Toggle
</Button>
<Button onClick={() => toggleValue(true)}>
    Make True
</Button>
<Button onClick={() => toggleValue(false)}>
    Make False
</Button>

useTimeout

Run a timeout without re-rendering issues. Useful for use in other hooks

const [count, setCount] = useState(10)
const { clear, reset } = useTimeout(() => setCount(0), 1000)

<Button onClick={() => setCount((c) => c + 1)}>
    Increment
</Button>
<Button onClick={clear}>
    Clear Timeout
</Button>
<Button onClick={reset}>
    Reset Timeout
</Button>

useDebounce

Run something after a certain delay. Does not run on the first time

const [count, setCount] = useState(10)
useDebounce(() => alert(count), 1000, [count])

<Button onClick={() => setCount((c) => c + 1)}>
    Increment
</Button>

useUpdateEffect

Only run when something changes. Does not run on the first time

const [count, setCount] = useState(10)
useUpdateEffect(() => alert(count), [count])

<Button onClick={() => setCount((c) => c + 1)}>
    Increment
</Button>

useArray

Easily use arrays.

const { array, set, push, remove, filter, update, clear } = useArray([1, 2, 3, 4, 5, 6])

<Button onClick={() => push(7)}>
    Add 7
</Button>
<Button onClick={() => update(1, 9)}>
    Change 2nd To 9
</Button>
<Button onClick={() => remove(1)}>
    Remove 2nd
</Button>
<Button onClick={() => filter((n) => n < 3)}>
    Keep below 4
</Button>
<Button onClick={() => set([1, 2])}>
    Set To 1, 2
</Button>
<Button onClick={clear}>
    Clear
</Button>

usePrevious

Store previous value of a state

const [count, setCount] = useState(0)
const [name, setName] = useState("Grant")
const previousCount = usePrevious(count)

<Button onClick={() => setCount((currentCount) => currentCount + 1)}>
    Increment
</Button>
<Button onClick={() => setName("John")}>
    Change Name
</Button>

useStateWithHistory

Stores the history of a state

const [count, setCount, { history, pointer, back, forward, go }] = useStateWithHistory(1)
const [name, setName] = useState("Grant")

<Button onClick={() => setCount((currentCount) => currentCount * 2)}>
    Double
</Button>
<Button onClick={() => setCount((currentCount) => currentCount + 1)}>
    Increment
</Button>
<Button onClick={back}>
    Back
</Button>
<Button onClick={forward}>
    Forward
</Button>
<Button onClick={() => go(2)}>
    Go To Index 2
</Button>
<Button onClick={() => setName("John")}>
    Change Name
</Button>

useStorage

Easily use Local or Session Storage

const [name, setName, removeName] = useSessionStorage("name", "Grant")
const [age, setAge, removeAge] = useLocalStorage("age", 26)

<Button onClick={() => setName("John")}>
    Set Name
</Button>
<Button onClick={() => setAge(40)}>
    Set Age
</Button>
<Button onClick={removeName}>
    Remove Name
</Button>
<Button onClick={removeAge}>
    Remove Age
</Button>

useAsync

Easily call an asynchronous function

const { loading, error, value } = useAsync(() => {
        return new Promise((resolve, reject) => {
            const success = true
            setTimeout(() => {
                success ? resolve("Hi") : reject("Error")
            }, 1000)
        })
    })

useFetch

Easily call and handle a fetch request

const [id, setId] = useState(1)
const { loading, error, value } = useFetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {}, [id])

Error: {JSON.stringify(error, null, 2)}
Results: {JSON.stringify(value, null, 2)}

<Button onClick={() => setId((currentId) => currentId + 1)}>
    Increment ID
<Button>


useClickOutside

Run a function when a click is outside the element

const [open, setOpen] = useState(false)
const modalRef = useRef()

useClickOutside(modalRef, () => {
    if (open) setOpen(false)
})
<div ref={modalRef} />

useCookie

Easily use cookies

const [value, update, remove] = useCookie("name", "John")

useCopyToClipboard

Copy to the clipboard

const [copyToClipboard, { success }] = useCopyToClipboard()

useDarkMode

Find if the Dark mode is set. Sets in local storage

const [darkMode, setDarkMode] = useDarkMode()

useDeepCompareEffect

Compare values within an object


useEffectOnce

Only run once

useEffectOnce(() => alert("Use Effect Once"))

useEventListener

Listen for events

const [key, setKey] = useState("")
useEventListener("keydown", (e: KeyboardEvent) => {
    setKey(e.key)
})

useGeolocation

Get the Geolocation Data

const { loading, error, data: { latitude, longitude } } = useGeolocation()

useMediaQuery

Check what media query is valid

const isLarge = useMediaQuery("(min-width: 200px)")

useOnScreen

Check if an element if on the screen

const secondRef = useRef()
const visible = useOnScreen(secondRef, "-100px")

<div ref={secondRef} />

useScript

Easily load a script asynchronous

const { loading, error } = useScript("https://code.jquery.com/jquery-3.6.0.min.js")

useSize

Find the size dynamically


useStateWithValidation

Easily validate a state

 const ref = useRef()
const size = useSize(ref)

<textarea ref={ref}></textarea>

useWindowSize

Check the size of the window

const { width, height } = useWindowSize()

Readme

Keywords

none

Package Sidebar

Install

npm i @grantpearceuk/hooks

Weekly Downloads

1

Version

1.0.1

License

none

Unpacked Size

81.2 kB

Total Files

134

Last publish

Collaborators

  • grantpearceuk