Skip to content

Instantly share code, notes, and snippets.

@codemile
Created June 29, 2021 18:31
Show Gist options
  • Save codemile/baab6720217d694acba4de1bcf32fa70 to your computer and use it in GitHub Desktop.
Save codemile/baab6720217d694acba4de1bcf32fa70 to your computer and use it in GitHub Desktop.
Hook that emits the previous and current values of useState()
import {useCallback, useState} from 'react';
export const useStatePair = <TType extends any>(initialState?: TType) => {
const [[prev, current], setPair] = useState<Array<TType | undefined>>([
undefined,
initialState
]);
const setValue = useCallback(
(next: TType) => setPair([current, next]),
[current]
);
return [prev, current, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment