0

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?

E.D
  • 831
  • 3
  • 16
  • 33

1 Answers1

0

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,
  }

}
Mina
  • 14,386
  • 3
  • 13
  • 26
  • Thx @Mina it's interesting, but I use this function to retrieve an image from a child component (I edited my question, sorry) – E.D Jul 20 '22 at 10:11
  • Never mind, but where is the `myLittleFunction` here ``, Also what is the issue you face when using this approach, if you use this function to retrieve an image from a child component? – Mina Jul 20 '22 at 10:47
  • myLittleFunction is in the parent component and I have no particular issue with setImage={setPickerResponse} , I can do the same, with the hook pass the function to it and instantly retrieve the image? – E.D Jul 20 '22 at 11:27
  • I think, there are no issues if you are using the custom hook, you can use the method and the state as if you declare in the component. – Mina Jul 20 '22 at 11:35
  • If the stuff isn't clear yet, please provide full example of code, you can use stackoverflow code snippet, or any live editors like codesandbox. – Mina Jul 20 '22 at 11:36
  • nope it works perfectly with a custom hook thx ;) – E.D Jul 20 '22 at 12:19