Skip to content

Instantly share code, notes, and snippets.

@RyanNorooz
Created August 24, 2022 21:57
Show Gist options
  • Save RyanNorooz/300c28125e99155b6055906f041544d2 to your computer and use it in GitHub Desktop.
Save RyanNorooz/300c28125e99155b6055906f041544d2 to your computer and use it in GitHub Desktop.
react useState hook with callback
import { useEffect, useRef, useState } from 'react'
type OnUpdateCallback<T> = (s: T) => void
type SetStateUpdaterCallback<T> = (s: T) => T
type SetStateAction<T> = (
newState: T | SetStateUpdaterCallback<T>,
callback?: OnUpdateCallback<T>
) => void
export function useStateEnhanced<T>(init: T): [T, SetStateAction<T>]
export function useStateEnhanced<T = undefined>(
init?: T
): [T | undefined, SetStateAction<T | undefined>]
export function useStateEnhanced<T>(init: T): [T, SetStateAction<T>] {
const [state, setState] = useState<T>(init)
const cbRef = useRef<OnUpdateCallback<T>>()
const setCustomState: SetStateAction<T> = (newState, callback?): void => {
cbRef.current = callback
setState(newState)
}
useEffect(() => {
if (cbRef.current) cbRef.current(state)
cbRef.current = undefined
}, [state])
return [state, setCustomState]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment