Skip to content

Instantly share code, notes, and snippets.

@julenwang
Created June 2, 2022 05:56
Show Gist options
  • Save julenwang/43f93ca24bb7a2fdd40703f52a97c310 to your computer and use it in GitHub Desktop.
Save julenwang/43f93ca24bb7a2fdd40703f52a97c310 to your computer and use it in GitHub Desktop.
useStateWithCallback.ts
import React, { useEffect, useRef, useState } from 'react';
export const useStateWithCallback = <T>(
initialState: T
): [state: T, setState: (updatedState: React.SetStateAction<T>, callback?: (updatedState: T) => void) => void] => {
const [state, setState] = useState<T>(initialState);
const callbackRef = useRef<(updated: T) => void>();
const handleSetState = (updatedState: React.SetStateAction<T>, callback?: (updatedState: T) => void) => {
callbackRef.current = callback;
setState(updatedState);
};
useEffect(() => {
if (typeof callbackRef.current === 'function') {
callbackRef.current(state);
callbackRef.current = undefined;
}
}, [state]);
return [state, handleSetState];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment