Skip to content

Instantly share code, notes, and snippets.

@ParrotStone
Forked from kyleshevlin/memoizedHandlers.js
Created January 22, 2021 21:22
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 ParrotStone/1fd2e06963f7a1765e3a12987d7d5188 to your computer and use it in GitHub Desktop.
Save ParrotStone/1fd2e06963f7a1765e3a12987d7d5188 to your computer and use it in GitHub Desktop.
Using React.useMemo to create a `handlers` object
// 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