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?

2
  • Could you provide more context to this? Commented Sep 3, 2021 at 6:58
  • 3
    I think Giovani has the answer below, but you should highly consider adding the React hooks eslint plugin to your project as it will flag this and inform you what is missing. Commented Sep 3, 2021 at 7:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing out, but is there a way to re-render only that card from where the onClick was triggered?
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.