2

I have a few components that all call the same function on an onPress handler, let's say it looks like the following:

function MyComponent () {
  const dispatch = useDispatch()

  const updateThing = React.useCallback((thingId: string) => {
    dispatch(someActionCreator(thingId))
    someGlobalFunction(thingId)
  }, [dispatch])

  return (
    <View>
      <NestedComponent onUpdate={updateThing} />
    </View>
  )
}

I want to move this function outside of the component so I can re-use it, thinking it would look something like this:

const updateThing = React.useCallback(myFunction)

However, it has a dependency of dispatch that I need to pass in and add to the dependency array.

How can I break this function out for reuse while also getting the performance gain from useCallback?

Alex
  • 8,353
  • 9
  • 45
  • 56

1 Answers1

11

You can write a custom hook like

export const useUpdateThinkg = () => {
  const dispatch = useDispatch()

  const updateThing = React.useCallback((thingId: string) => {
    dispatch(someActionCreator(thingId))
    someGlobalFunction(thingId)
  }, [dispatch])
  return { updateThing };
}

And then use it like

import { useUpdateThing } from 'path/to/updateThing'
function MyComponent () {
  const { updateThing} = useUpdateThing();

  return (
    <View>
      <NestedComponent onUpdate={updateThing} />
    </View>
  )
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    Brilliant answer - thank you. It's taking a while to get used to thinking in Hooks but what an elegant solution. Will accept answer when SO lets me in a few minutes. – Alex May 08 '20 at 13:08
  • 1
    Glad to have helped Alex :-) and yeah hooks are a bit of a learning curve – Shubham Khatri May 08 '20 at 13:08