0

I have a list of cards. When I add them to favourites by pressing a button, it changes the color of that button. However, I just want that particular card to re-render after adding to favourites.

const addFavouriteHandler = useCallback((id: number) => {
   dispatch(addFav(id));
}, [ ?? ])

// This is my card in the list
<MovieCard
   key={movie.id}
   movie={movie}
   addFavourite={addFavouriteHandler}
   removeFavourite={removeFavouriteHandler}
   isFavourite={isFavourite}
/>

What would be the dependencies of the useCallback here?

Lokesh Bajracharya
  • 457
  • 2
  • 8
  • 19
  • Could you provide more context to this? – Ryan Le Sep 03 '21 at 06:58
  • 3
    I think Giovani has the answer below, but you should ***highly*** consider adding the [React hooks eslint plugin](https://reactjs.org/docs/hooks-rules.html#eslint-plugin) to your project as it will flag this and inform you what is missing. – Drew Reese Sep 03 '21 at 07:06

1 Answers1

1

Most probably you got a warning on missing dependency for dispatch function, so your useCallback would be:

const addFavouriteHandler = useCallback((id: number) => {
   dispatch(addFav(id));
}, [dispatch]);

The real problem is that I don't think you need a custom hook in this case, just write:

const addFavouriteHandler = (id: number) => {
   dispatch(addFav(id));
};

Then, if you want to render MovieCard after you added it to favourites, if isFavourite is something like:

isFavourite = arrayOfFavourites.includes(movie.id)

where arrayOfFavourites is the array filled by dispatch(addFav(id));, then your MovieCard will be for sure re-rendered because now card id is on arrayOfFavourites.

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
  • Thanks for pointing out, but is there a way to re-render only that card from where the `onClick` was triggered? – Lokesh Bajracharya Sep 03 '21 at 07:23
  • @LokeshBajracharya its just necessary to connect the `MovieCard` state to something that will change when you add the card to favourites. I think in `MovieCard` you have something on html that is connected to `isFavourite` prop (an icon on card that means that card is a favourite card). In this case, card will be re-rendered. Is my assumption on `MovieCard` wrong? – Giovanni Esposito Sep 03 '21 at 07:35