skip to Main Content

I am using useCallback to memo my callback function but it doesn’t seem to work with currying function, my PhotoItem component always re-render when MyListPhoto re-render although I wrapping my PhotoItem in React.memo(). Because handleDelete function is a currying function, is there any way to use with useCallback ?

const MyListPhoto = () => {
   ...other state...
   const { delete } = useDeletePhoto();

   // always create new function when component re-render
   const handleDelete = useCallback((index) => (photoId) => {
      delete(photoId, index)
   }, []);

   return (
     <ul>
        {photos.map((photo, index) => (
           <PhotoItem key={photo.id} photo={photo} onDelete={handleDelete(index)}  />
     </ul>
   )
}

PhotoItem component:

const PhotoItem = React.memo(({ photo, onDelete }) => {
    console.log('re-render');

    return (
      ...
    )
})

2

Answers


  1. You have to memoize each function

    const MyListPhoto = () => {
      // ...other state...
      const { del } = useDeletePhoto();
    
      const deleteHandlers = useMemo(() => {
        return photos.map((photo, index) => (photoId) => del(photoId, index));
      }, [photos]);
    
      return (
        <ul>
          {photos.map((photo, index) => (
            <PhotoItem
              key={photo.id}
              photo={photo}
              onDelete={deleteHandlers[index]}
            />
          ))}
        </ul>
      );
    };
    
    Login or Signup to reply.
  2. Sorry, I didn’t get the point! Why do you need to memorize the function?
    how about this:

    ...
    return <ul>
            {photos.map((photo, index) => (
               <PhotoItem key={photo.id} photo={photo} onDelete={() => delete(photo.id, index)}  />
         </ul>
       )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search