Search code examples
javascriptreact-nativefunctionusecallback

utility function with useCallback


I have a simple function with a useCallback in three part of my app to set an image:

const myLittleFunction = useCallback((image: string | undefined) => {
    mySetState(image)
  }, [
    mySetState,
  ])

this function is used to retrieve an image of a child component:

<MyChildComponent
  setImage={setPickerResponse}
  />

But since I have 3 times the same one in three different places, how could I make it a single utility function?


Solution

  • I think you may need to move the STATE and the useCallback function in a custom hook, and you can use it in multiple places.

    Ex:

    export default () => {
    
      const [myState, setMyState] = useState('value here')
      const myLittleFunction = useCallback((image: string | undefined) => {
        mySetState(image)
      }, [
        mySetState,
      ])
    
      return {
        myState,
        setMyState,
        myLittleFunction,
      }
    
    }