Skip to content

Instantly share code, notes, and snippets.

@noherczeg
Created March 12, 2024 15:51
Show Gist options
  • Save noherczeg/57587c508458761a11443316510b2049 to your computer and use it in GitHub Desktop.
Save noherczeg/57587c508458761a11443316510b2049 to your computer and use it in GitHub Desktop.
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