Created
January 22, 2021 00:26
-
-
Save kyleshevlin/08a2deb904b79077e46966567ccabf06 to your computer and use it in GitHub Desktop.
Using React.useMemo to create a `handlers` object
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
// One of my new favorite React Hook patternms is to create handler | |
// functions for a custom hook using `React.useMemo` instead of | |
// `React.useCallback`, like so: | |
function useBool(initialState = false) { | |
const [state, setState] = React.useState(initialState) | |
// Instead of individual React.useCallbacks gathered into an object | |
// Let's memoize the whole object. Then, we can destructure the | |
// methods we need in our consuming component. | |
const handlers = React.useMemo(() => ({ | |
setTrue: () => { setState(true) }, | |
setFalse: () => { setState(false) }, | |
toggle: () => { setState(s => !s) }, | |
reset: () => { setState(initialState) }, | |
}), [initialState]) | |
return [state, handlers] | |
} | |
// Makes it super simple to make a whole bunch of methods stable, | |
// preventing unnecessary rerenders |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting pattern @kyleshevlin, thanks for sharing!
Can you explain why you are passing
initialState
as a dependency for theuseMemo
call? I'm not sure how that could change between re-renders.Thanks.