Skip to content

Instantly share code, notes, and snippets.

@mohitPassan
Created June 12, 2022 19:26
Show Gist options
  • Save mohitPassan/5b7783ac0ea233f367e8db865d4e02a7 to your computer and use it in GitHub Desktop.
Save mohitPassan/5b7783ac0ea233f367e8db865d4e02a7 to your computer and use it in GitHub Desktop.
Custom hook to enable callback function for hooks
import { useStateWithCallback } from "./useStateWithCallback";
const App = () => {
const [bananas, setBananas] = useStateWithCallback(0);
const eatMore = () => {
setBananas(bananas + 1, (prevValue, newValue) => {
console.log(newValue);
});
};
const shitSome = () => {
setBananas(bananas - 1, (prevValue, newValue) => {
console.log(newValue);
});
};
return (
<div
style={{
paddingLeft: "15px",
}}
>
<p>I have eaten {bananas} bananas</p>
<button onClick={eatMore}>Eat more</button>
<button onClick={shitSome}>Shit some</button>
</div>
);
};
export default App;
...
const [bananas, setBananas] = useStateWithCallback(0);
const eatMore = () => {
setBananas(bananas + 1, (prevValue, newValue) => {
console.log(newValue);
});
};
const shitSome = () => {
setBananas(bananas - 1, (prevValue, newValue) => {
console.log(newValue);
});
};
...
import { useState } from "react";
const useStateWithCallback = (initialValue) => {
const [value, setValue] = useState(initialValue);
const setValueAndCallback = (newValue, callback) => {
setValue(prevValue => {
if (callback) {
callback(prevValue, newValue);
}
return newValue;
});
};
return [value, setValueAndCallback];
}
export { useStateWithCallback};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment