0

I'm creating a similar to netflix app. I have the below use case:

movies.map((movie) => (
   <Grid item key={movie.imdbID}>
      <Card movie={movie} onIconClick={onIconClick} />
   </Grid>
))

I'm wrapping Card component under React.memo but even when one of the movie (watched flag inside it) changes, all the Cards get rendered.
Somehow Card is not getting memoized.
What I might be doing wrong?

How do I prevent re-rendering of all the movies when user has only clicked one card and only that card needs to be updated?

  • Please provide the problem example in codesandbox – Nisharg Shah Aug 15 '21 at 17:21
  • 1
    onIconClick is a function and it won't work under React.memo try useCallback for onIconClick function and send the memoized onIconClick function to Card component – pageNotfoUnd Aug 15 '21 at 17:56
  • https://codesandbox.io/s/adoring-framework-553c0?file=/src/App.js this is the link. I created just to explain my issue. So when I am only changing a single movie then why all the movies are getting rendered? I get console 3 times when I click the first movie name. – Isha Mahajan Aug 15 '21 at 18:05
  • Read https://dmitripavlutin.com/use-react-memo-wisely/#4-reactmemo-and-callback-functions, to understand the issue and use 'useCallback' to solve the issue also pointed out in the blog. – tarzen chugh Aug 15 '21 at 18:10
  • @tarzenchugh will it be possible for you to edit my sandbox link to provide the solution? I tried it myself but didnt work! – Isha Mahajan Aug 15 '21 at 18:12
  • @IshaMahajan Can you try this link https://codesandbox.io/s/jolly-poitras-mvc2f?file=/src/StaticChildComp.js:322-330, seems to be an issue with movie object equality issue and let me know if that works for you. – tarzen chugh Aug 15 '21 at 19:01
  • It only renders again in virtual dom and doesn't have much effect on actual dom. Only the changed card will be updated in actual dom. – Kavindu Vindika Aug 15 '21 at 19:50
  • @K.vindi but my cards have an image at center. And when I update one of the cards, other cards which have only alt image (image couldnt download due to error), flicker due to re-rendering. Thats how I came to know that they are being re-rendered. – Isha Mahajan Aug 16 '21 at 03:20

0 Answers0