Home > Net >  Memoize a function in parent before passing it to children to avoid rerender React
Memoize a function in parent before passing it to children to avoid rerender React

Time:12-11

I'm building a chat app, I have 3 main components from parent to child in this hierarchical order: Chat.js, ChatLine.js, EditMessage.js. I have a function updateMessage in Chat component that I need to pass to the second child EditMessage, but it causes a rerender of every ChatLine when I click on Edit button and begin typing. I can't figure out how to memoize it so it only causes a rerender on the ChatLine I'm editing.

It only works if I pass it to ChatLine as :

updateMessage={line.id === editingId ? updateMessage : null}

instead of :

updateMessage={updateMessage}

But I want to avoid that and memoize it instead so it doesn't cause a rerender after each letter I type while editing a message.

This is the whole code: (also available in Edit memoize-a-function-in-parent-before-passing-it-to-children-to-avoid-rerender-rea

  • Related