Created
May 15, 2023 15:04
-
-
Save vagnerlandio/e42b8fbab0a61e60878b614e4e3e430f to your computer and use it in GitHub Desktop.
TypeScript function to simulate React.useState with callback
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
import { useStateWithCallback } from './useStateWithCallback'; | |
function MyComponent() { | |
const [count, setCount] = useStateWithCallback(0, (value) => { | |
console.log(`Count updated: ${value}`); | |
}); | |
function increment() { | |
setCount(count + 1, () => { | |
console.log(`Count incremented: ${count + 1}`); | |
}); | |
} | |
return ( | |
<div> | |
<p>Count: {count}</p> | |
<button onClick={increment}>Increment</button> | |
</div> | |
); | |
} |
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
/** | |
* A function that simulates the React.useState hook with a callback parameter. | |
* | |
* @template T The type of the state value. | |
* | |
* @param {T} initialValue The initial value for the state. | |
* @param {(value: T) => void} callback The callback function to be called after the state has been updated. | |
* | |
* @returns {[T, (newValue: T, callback?: () => void) => void]} A tuple containing the current state value and a function to update the state. | |
*/ | |
function useStateWithCallback<T>(initialValue: T, callback: (value: T) => void): [T, (newValue: T, callback?: () => void) => void] { | |
const [state, setState] = React.useState<T>(initialValue); | |
const setStateWithCallback = React.useCallback((newValue: T, callback?: () => void) => { | |
setState(newValue); | |
if (callback) { | |
callback(); | |
} | |
}, []); | |
React.useEffect(() => { | |
callback(state); | |
}, [state, callback]); | |
return [state, setStateWithCallback]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment