Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active October 31, 2021 14:09
Show Gist options
  • Save Ivannnnn/7239ffef45d1046a4b0df202056356c7 to your computer and use it in GitHub Desktop.
Save Ivannnnn/7239ffef45d1046a4b0df202056356c7 to your computer and use it in GitHub Desktop.
Hooks
function usePrevious(value) {
const ref = useRef()
useEffect(() => {
ref.current = value
}, [value])
return ref.current
}
const useRepetableArray = (array, initial) => {
const [state, setState] = useState(initial)
const next = useCallback(
(function () {
let index = array.findIndex((val) => val === initial)
return () => {
if (++index >= array.length) index = 0
setState(array[index])
}
})(),
[]
)
return [state, next]
}
const useUpdated = (cb, dependencies) => {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current && cb()
}, dependencies)
useEffect(() => {
isMounted.current = true
}, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment