0

Learning React and in particular memoization and useCallback hook and I have a doubt about something. Here is my snippet :

const updateCardImage = useCallback((event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = () => {
        setCardData(cardData => ({...cardData, picture: reader.result}));
    };
    reader.readAsDataURL(file);
}, []);

https://github.com/JSchoreels/wishlist-manager-web/blob/27eb52fe65575fc8d0d13ad1a73ca7381882a859/src/components/WishlistCardCreator.js#L91-L98

You can also try it live there : https://jschoreels.github.io/wishlist-manager-web

As you can see, at some point in the function I use cardData, however, it's used through the function setCardData(cardData => output) and not setCardData(output)

In this case, if I understand correctly useCallback, I do not have to specify anything in the deps, because my function can stay the same for any future call since it does not rely on the current state, but I would have to add [cardData] as a dep if I was using setCardData({...cardData, picture: reader.result}); instead ?

The code seem to run fine, but I just want to be sure I'm not doing anything more subtely wrong.

Jonathan Schoreels
  • 1,660
  • 1
  • 12
  • 20

0 Answers0