Skip to content

Instantly share code, notes, and snippets.

@timbryandev
Created December 2, 2021 13:49
Show Gist options
  • Save timbryandev/d3ffbb7b2c83ce830d2748f38258c393 to your computer and use it in GitHub Desktop.
Save timbryandev/d3ffbb7b2c83ce830d2748f38258c393 to your computer and use it in GitHub Desktop.
A collection of hooks I've found handy for use in React functional components
/**
*
* @param {function} effect
* @param {array} deps
* @param {number} delay
*/
export const useDebouncedEffect = (effect, deps = [], delay = 100) => {
useEffect(() => {
const handler = setTimeout(() => effect(), delay)
return () => clearTimeout(handler)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...deps, delay])
}
/**
*
* @param {string} key
* @param {any} initialValue
* @returns {string | object}
*/
export const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (err) {
console.warn(err)
return initialValue
}
})
const setValue = value => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (err) {
console.error(err)
}
}
return [storedValue, setValue]
}
/**
*
* @param {string} key
* @param {any} initialValue
* @returns {string | object}
*/
export const useSessionStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.sessionStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (err) {
console.warn(err)
return initialValue
}
})
const setValue = value => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.sessionStorage.setItem(key, JSON.stringify(valueToStore))
} catch (err) {
console.error(err)
}
}
return [storedValue, setValue]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment