Skip to content

Instantly share code, notes, and snippets.

@neatshell
Created July 6, 2023 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neatshell/f11761a766ede0d98879cc27a14b1b56 to your computer and use it in GitHub Desktop.
Save neatshell/f11761a766ede0d98879cc27a14b1b56 to your computer and use it in GitHub Desktop.
useStateWithCallback like old setState callback behaviour
// https://betterprogramming.pub/synchronous-state-in-react-using-hooks-dc77f43d8521
import { useState } from 'react';
export function useStateWithCallback<T>(initialValue: T) {
const [value, setValue] = useState(initialValue);
const setValueAndCallback = (newValue: T, callback: (prevValue: T, newValue: T) => void) => {
setValue((prevValue) => {
if (callback) {
callback(prevValue, newValue);
}
return newValue;
});
};
return [value, setValueAndCallback];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment