Search code examples
javascriptreactjsreact-nativereact-hooksusecallback

Reuse React.useCallback() function across multiple components


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?


Solution

  • 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>
      )
    }