Created
July 6, 2023 14:27
-
-
Save neatshell/f11761a766ede0d98879cc27a14b1b56 to your computer and use it in GitHub Desktop.
useStateWithCallback like old setState callback behaviour
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
// 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