Created
June 12, 2022 19:26
-
-
Save mohitPassan/5b7783ac0ea233f367e8db865d4e02a7 to your computer and use it in GitHub Desktop.
Custom hook to enable callback function for hooks
This file contains 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"; | |
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; |
This file contains 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
... | |
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); | |
}); | |
}; | |
... |
This file contains 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 { 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