-
-
Save hermanho/f7a0e36f0385524e3ad219f02a52516a to your computer and use it in GitHub Desktop.
Custom hook to enable callback function for hooks
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"; | |
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 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
... | |
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 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 { 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