npm package: @grantpearceuk/hooks
Description: View hooks in action (Examples)
Latest version: 1.0.1

# Custom React Hooks

View hooks in action (Examples)

## useToggle

Easily toggle between a boolean

```tsx

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

```tsx

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

```tsx

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

```tsx

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

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

```

---

## useArray

Easily use arrays.

```tsx

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

```tsx

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

```tsx

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

```tsx

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

```tsx

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

```tsx

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

```tsx

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

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

```

---

## useCookie

Easily use cookies

```tsx

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

```

---

## useCopyToClipboard

Copy to the clipboard

```tsx

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

```

---

## useDarkMode

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

```tsx

const [darkMode, setDarkMode] = useDarkMode()

```

---

## useDeepCompareEffect

Compare values within an object

---

## useEffectOnce

Only run once

```tsx

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

```

---

## useEventListener

Listen for events

```tsx

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

```

---

## useGeolocation

Get the Geolocation Data

```tsx

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

```

---

## useMediaQuery

Check what media query is valid

```tsx

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

```
---

## useOnScreen

Check if an element if on the screen

```tsx

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

<div ref={secondRef} />

```

---

## useScript

Easily load a script asynchronous

```tsx

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

```

---

## useSize

Find the size dynamically

---

## useStateWithValidation

Easily validate a state

```tsx

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

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

```

---

## useWindowSize

Check the size of the window

```tsx

const { width, height } = useWindowSize()

```

---