Skip to content

Instantly share code, notes, and snippets.

@vagnerlandio
Created May 15, 2023 15:04
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 vagnerlandio/e42b8fbab0a61e60878b614e4e3e430f to your computer and use it in GitHub Desktop.
Save vagnerlandio/e42b8fbab0a61e60878b614e4e3e430f to your computer and use it in GitHub Desktop.
TypeScript function to simulate React.useState with callback
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>
);
}
/**
* 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