Created
March 12, 2024 15:51
-
-
Save noherczeg/57587c508458761a11443316510b2049 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { type SetStateAction, type Dispatch, useEffect, useRef, useState, useMemo } from 'react'; | |
export function useDerivedState<T>(prop: T): [T, Dispatch<SetStateAction<T>>] { | |
const [internalVal, setInternalVal] = useState<T>(prop); | |
const previousProp = useRef<any>(null); | |
useEffect(() => { | |
if (previousProp.current !== prop) { | |
previousProp.current = prop; | |
setInternalVal(prop); | |
} | |
}, [prop]); | |
const result = useMemo<[T, Dispatch<SetStateAction<T>>]>(() => ([internalVal, setInternalVal]), [internalVal]); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment